Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong Output for java.text.SimpleDateFormat while Reading "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZZ"

I was trying to convert the date in String format into java.util.Date by using java.text.SimpleDateFormat, however it's not giving me the right output. Please help!

My input is generated by Django date: ex. "2014-01-20T07:17:06.150995+00:00"

But, I got "Mon Jan 20 15:19:36 GMT+08:00 2014" instead of "Mon Jan 20 15:17:06 GMT+08:00 2014"

Here's my testing code:

String s = "2014-01-20T07:17:06.150995+00:00";

SimpleDateFormat sdf;
String fmt = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZZ";
sdf = new SimpleDateFormat(fmt, Locale.US);

String result = "";
try {
    Date date = sdf.parse(s);
    Log.d(Constants.LOG_TAG, date.toString());
    result = date.toString();
} catch (Exception e) {
    Log.d(Constants.LOG_TAG, "date formatting error" + e.getMessage());
}
Log.d(Constants.LOG_TAG, "date test >> " + result);
like image 621
Heron Yang Avatar asked Dec 26 '22 14:12

Heron Yang


1 Answers

As you can see your two dates differ by 2.5 minutes.

This happens because you are parsing microseconds as milliseconds. This will add 150000 milliseconds to your result, or 2.5 minutes.

There is no standard way to parse a date string with microseconds using SimpleDateFormat, you will have to do it yourself if you can't get the source string in a different format.

If the date is always in exactly this format you could do something like:

String dateWithoutMicros = s.substring(0, s.length() - 9) + s.substring(s.length() - 6);
Date date = sdf.parse(dateWithoutMicros);
like image 134
Keppil Avatar answered Mar 30 '23 00:03

Keppil