joe joe - 2 months ago 10
Android Question

Calculating time difference between two differently formated dates

I know there are million similar questions about this, but I struggle to find the right answer, so I'll appreciate if someone can give me straight answer.

I have some date in string from backend in this format:

String days = "2016-12-01T15:43:42.2737987+01:00";

my simple day formatter looks like this:

private DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.getDefault());

I'm trying to get todays date this way:

String currentDateandTime = sdf.format(new Date());

and my method for calculating difference in days looks like this:

public void daysBetween(String date1, String date2) {
Date mDate1;
Date mDate2;
try {
mDate1 = sdf.parse(date1);
mDate2 = sdf.parse(date2);
dateDiff = (mDate1.getTime() - mDate2.getTime()) / (24 * 60 * 60 * 1000);
days = String.valueOf(dateDiff);
} catch (Exception e) {

So the problem here is, I can't parse "days" string because, sometimes I get 7 digits for seconds, sometimes 2, and so on... Is there a way to adjust those two dates to get the days difference?

String formatedDays = days.substring(0,18)+ days.substring(days.lastIndexOf("+"));

This will make you date string with only the seconds and will have the timezone in it