Which date format does Java handle correctly?

I have code like the following:

import java.text.DateFormat;
...

this.timestampFormat = new SimpleDateFormat(timestampFormat, Locale.UK);
this.timestampFormat.parse(modifyTimestamp.get().toString());

      

But parsing generates an error:

Caused by: java.text.ParseException: Unparseable date: "20150429142243.925Z"

      

I've tried both of these date format strings:

yyyyMMddHHmmss'Z'
yyyyMMddHHmmss'.0Z'

      

The "925Z" part of the time I think is the problem. If the string of the second date format is correct in this case, although it doesn't work.

+3


source to share


3 answers


Try the following:

SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss.SSS'Z'", Locale.UK);

      



925 is millisecond, so you need SSS

to represent that.

+4


source


You are injecting String also milliseconds



SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss.SSS'Z'", Locale.UK);

      

+4


source


Joda time

Similar to the accepted correct answer, but using the Joda-Time library.

String input = "20150429142243.925Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern ( "yyyyMMddHHmmss.SSSZ" );
DateTime dateTime = formatter.parseDateTime ( input ).withZone ( DateTimeZone.UTC );

      

No locale required

In this case, there is no need for Locale

. It only needs to parse the day or month name. With only numbers and known ordering, there is no need for Locale.

Don't confuse Locale for timezone . These are orthogonal problems. If you want the UK timezone , apply it explicitly using the proper timezone name (never 3 or 4 letter codes).

Sample code, again using Joda-Time 2.8.

dateTimeEuropeLondon = dateTime.withZone( DateTimeZone.forID( "Europe/London" ) ;

      

ISO 8601

If your string had T

between the date part and the time of day, it would conform to the base formats defined by ISO 8601 . You can use one of the ISO-compatible formatters built into Joda-Time rather than explicitly specifying the template.

String input = "20150429T142243.925Z";  // "T" separator inserted in middle.
DateTime dateTime = DateTimeFormatter.basicDateTime().parseDateTime ( input ).withZone ( DateTimeZone.UTC );

      

java.time

Java 8 and later comes with the successor to Joda-Time, the java.time framework ( Tutorial ).

Unlike Joda-Time, the predefined java.time formats do not have a "basic" version , not displaying the HYPHEN-MINUS and COLON characters, so we must explicitly define the template for formatting.

String input = "20150429142243.925Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyyMMddHHmmss.SSSX" ).withZone( ZoneOffset.UTC );
ZonedDateTime zdt = ZonedDateTime.parse( input , formatter );

      

Dump for console.

System.out.println( "zdt : " + zdt );

      

At startup.

zdt: 2015-04-29T14: 22: 43.925Z

0


source







All Articles