Reputation: 2622
I am trying to parse a date string into a java.util.Date
using java.text.SimpleDateFormat
; however, the resulting formatted date is wrong.
Here is a test case showing the issue:
@Test
public void testSimpleDateFormat() throws Exception {
String dateString = "2016-03-03 11:50:39.5960000";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSSS");
Date date = format.parse(dateString);
assertEquals(dateString, format.format(date));
}
This results in the following failure:
org.junit.ComparisonFailure:
Expected :2016-03-03 11:50:39.5960000
Actual :2016-03-03 13:29:59.0000000
The date is correct, but the hours, minutes, seconds, and milliseconds are all wrong. Why is java.text.SimpleDateFormat
messing up the time on my date?
Upvotes: 2
Views: 346
Reputation: 338181
You are using old classes that have proven to be confusing, troublesome, and poorly designed. Avoid them. They have been supplanted by the java.time framework built into Java 8 and later.
The java.time classes use resolution of nanoseconds, for up to nine digits of a decimal fraction of second. More than enough for your six digits (microseconds).
Your input string is close to the standard ISO 8601 format. That format is used by default in java.time for parsing/generating string representations of date-time values. So, need to specify parsing pattern.
Morph your input string into standard format. Replace the SPACE in the middle with a T
.
String input = "2016-03-03 11:50:39.5960000";
String inputStandardized = input.replace( " " , "T" );
Parse that string into a date-time object.
LocalDateTime ldt = LocalDateTime.parse( inputStandardized );
To get an actual moment on the timeline, assign an offset or time zone intended for this input.
If in UTC, create a OffsetDateTime
.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC );
If a specific time was intended, create a ZonedDateTime
.
ZonedDateTime zdt = ldt.atZone( ZoneId.of( "America/Montreal" ) ) ;
If you do not yet have Java 8 technology available, consider adding either the backport of java.time or Joda-Time (the inspiration for java.time). For Android, there is a specific wrapper of the backport, ThreeTenABP.
Upvotes: 0
Reputation: 691635
Your pattern says that 5960000
is a number of milliseconds. That represents 5960 seconds, so approximately 1 hour and 39 minutes, which explains the difference between the date you obtain and the initial one.
Upvotes: 8