Reputation: 741
I'm converting a string to Date in Java, but I having a problem It is adding some extra minutes to the result Date.
The String has the following format "yyyy-MM-dd HH:mm:ss.sss" and I have created this function:
public static Date parseISO8601(String date) {
Date result = null;
try {
if (!TextUtils.isEmpty(date)) {
SimpleDateFormat dateFormat = new SimpleDateFormat(
ISO8601_DATE_FORMAT);
result = dateFormat.parse(date);
}
}
catch (Exception ex){
return null;
}
return result;
}
public static final String ISO8601_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.sss";
When I use this function with this string "2015-06-11 20:17:56.873" the result is "Thu Jun 11 20:31:33 CST 2015". I am really new coding with Java, I have read a lot of posts but for me everything seems normal, I don´t know why this is happening.
Some ideas?
Upvotes: 2
Views: 234
Reputation: 10945
You want to use yyyy-MM-dd HH:mm:ss.SSS
, which uses "SSS" (milliseconds) instead of "sss" (seconds).
With a format of yyyy-MM-dd HH:mm:ss.sss
you are specifying the seconds field twice, so you are effectively trying to format a date-time of "2015-06-11 20:17:56 oh-wait-I-mean-873-seconds", which is why the resultant time is off by ~14 minutes.
Upvotes: 4
Reputation: 1741
Replace yyyy-MM-dd HH:mm:ss.sss
with yyyy-MM-dd HH:mm:ss.SSS
As per http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
s --> second
S --> milliseconds
Upvotes: 1
Reputation: 13137
Try this instead:
yyyy-MM-dd HH:mm:ss.SSS
You are using 's' instead of 'S" for millis.
Upvotes: 6