Thunderhashy
Thunderhashy

Reputation: 5321

Java dateformatter

Is there an easy way to parse the following 2 types of String to Date in Java

2013-11-22T18:37:55.645+0000
2013-11-22T14:20:30.645Z

Both mean the same thing, but I am having to use 2 different date format patterns

yyyy-MM-dd'T'HH:mm:ss.SSSZ
yyyy-MM-dd'T'HH:mm:ss.SSS'Z'

and I want to do it with only 1 pattern.

Upvotes: 1

Views: 456

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 338181

Both of your format patterns are variations of the same, ISO 8601.

Easy in Joda-Time 2.3.

One line of code, using Joda-Time's built-in ISO 8601 formatter. That formatter handles both offsets, either zeros or a Z.

org.joda.time.format.ISODateTimeFormat.dateTime().withZoneUTC().parseDateTime( eitherStringGoesHere );

More detailed code…

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.

String dateTimeStringZero = "2013-11-22T18:37:55.645+0000";
String dateTimeStringZulu = "2013-11-22T18:37:55.645Z";

org.joda.time.DateTime dateTimeZero = org.joda.time.format.ISODateTimeFormat.dateTime().withZoneUTC().parseDateTime( dateTimeStringZero );
org.joda.time.DateTime dateTimeZulu = org.joda.time.format.ISODateTimeFormat.dateTime().withZoneUTC().parseDateTime( dateTimeStringZulu );

Output…

System.out.println( "dateTimeZero: " + dateTimeZero );
System.out.println( "dateTimeZulu: " + dateTimeZulu );

When run…

dateTimeZero: 2013-11-22T18:37:55.645Z
dateTimeZulu: 2013-11-22T18:37:55.645Z

If you want a time zoned DateTime, change out the withZoneUTC(). See the withZone method. For user’s default time zone, simply omit any time zone call.

Upvotes: 1

chaos
chaos

Reputation: 681

Have you tried this:

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
    Date dt1 = sdf.parse(str1);

Upvotes: 0

AlexR
AlexR

Reputation: 115328

Yes, there is a very simple way called SimpleDateFormat. Send your format to constructor of this class and format date according to your spec.

Upvotes: 1

Related Questions