String-Date conversion with nanoseconds

Viewed 56920

I've been struggling for a while with this piece of code for an Android app and I can't get the hang of it. I've read and tried every solution I found on stackoverflow and other places, but still no luck.

What I want to do is have a function to convert a string like "17.08.2012 05:35:19:7600000" to a UTC date and a function that takes an UTC date and converts it to a string like that.

String value = "17.08.2012 05:35:19:7600000";
DateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss:SSSSSSS");
try
{
  Date today = df.parse(value);
  System.out.println("Today = " + df.format(today) + " " + today.toGMTString());
} 
catch (ParseException e)
{
  e.printStackTrace();
}

This results in : Today = 17.08.2012 07:41:59:0000000 17 Aug 2012 04:41:59 GMT which are both wrong.

I tried setting SDF's timezone to UTC, no luck.
Another thing that I noticed: if I do df.setLenient(false);
It gives me : java.text.ParseException: Unparseable date: "17.08.2012 05:35:19:7600000" .

If anyone can provide me with some explanations / sample code, I would be very grateful. Thanks in advance

5 Answers

To drop the nanoseconds, use:

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.")

Update: java.time

The Question and other Answers use terrible date-time classes that are now legacy. These flawed classes were years ago supplanted by the modern java.time classes defined in JSR 310. Avoid Calendar, DateFormat, Date, etc.

Define a formatting pattern with DateTimeFormatter.

String input = "17.08.2012 05:35:19:7600000";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM.uuuu HH:mm:ss:SSSSSSS" );

Parse.

LocalDateTime ldt = LocalDateTime.parse( input , f ) ;

A LocalDateTime object represents a date with a time of day, but lacks the context of a time zone or offset from UTC.

If you are certain the input text is intended to represent a moment as seen in UTC, having an offset of zero hours-minutes-seconds, then assign a ZoneOffset to produce an OffsetDateTime object.

OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;

See this code run live at Ideone.com.

ISO 8601

I suggest you educate the publisher of your data about the use of ISO 8601 standard formats when serializing date-time values to text.

The java.time classes use ISO 8601 formats by default when parsing/generating text.

Related