Java Time Zone When Parsing DateFormat
Asked Answered
C

9

15

I had code that parses date as follows:

String ALT_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
SimpleDateFormat sdf = new SimpleDateFormat(
                    ALT_DATE_TIME_FORMAT);
Date date = sdf.parse(requiredTimeStamp);

And it was working fine, suddenly, this stopped working. It turns out an admin made some config changes on the server and the date is currently being returned as "2010-12-27T10:50:44.000-08:00" which is not parse-able by the above pattern. I have two questions:

The first would be what pattern would parse the date being returned by the JVM in the format above (specifically, just '-08:00' as the time zone)? And second, where exactly would one change such settings on a linux RHEL 5 server so that we are aware of such changes in the future?

Cassaundra answered 27/12, 2010 at 23:44 Comment(0)
G
4

The other application is using the ISO 8601 dateTime format. I am assuming the other application is sending you an XML response that is in compliance with XML Schema's dateTime type, which is ISO 8601. Now, it is a known thing that the DateFormat can't parse this format. You either have to use other libraries like joda-time (joda-time is the winner) or the FastDateFormat as specified in the other responses. Look at this post Converting ISO 8601-compliant String to java.util.Date

Grazynagreabe answered 28/12, 2010 at 1:1 Comment(1)
The Joda-Time library works but is now in maintenance mode. The team advises migration to the java.time classes.Fustigate
F
33

tl;dr

OffsetDateTime.parse( "2010-12-27T10:50:44.000-08:00" )

ISO 8601

The input string format is defined in the ISO 8601 standard, a family of date-time formats.

Avoid old date-time classes

The Question and other Answers use old outmoded date-time classes bundled with the earliest versions of Java. Avoid them. Now supplanted by the java.time classes.

Using java.time

Your input string ends with an offset-from-UTC. So we parse as a OffsetDateTime object.

The java.time classes use ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.

OffsetDateTime odt = OffsetDateTime.parse( "2010-12-27T10:50:44.000-08:00" );

If you want to view this date-time value as a moment on the timeline in UTC, extract an Instant.

Instant instant = odt.toInstant();

A time zone is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST). If you have a time zone in mind, apply a ZoneId to get a ZonedDateTime object. Same moment on the timeline, but viewed through a different wall-clock time.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = odt.atZoneSameInstant( z );  // Same moment on the timeline, but viewed through a different wall-clock time.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Fustigate answered 5/9, 2016 at 21:27 Comment(0)
G
4

The other application is using the ISO 8601 dateTime format. I am assuming the other application is sending you an XML response that is in compliance with XML Schema's dateTime type, which is ISO 8601. Now, it is a known thing that the DateFormat can't parse this format. You either have to use other libraries like joda-time (joda-time is the winner) or the FastDateFormat as specified in the other responses. Look at this post Converting ISO 8601-compliant String to java.util.Date

Grazynagreabe answered 28/12, 2010 at 1:1 Comment(1)
The Joda-Time library works but is now in maintenance mode. The team advises migration to the java.time classes.Fustigate
A
2

if still looking for answer, this worked for me

My Input : 2020-12-08T10:36:53.939+05:30
My Output : Tue Dec 08 10:36:53 IST 2020

You can convert this date to any format you need !

private static Date convertDate(String input) {
    Date newDate = null;
    try {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
        newDate=dateFormat.parse(input);  
    } catch (Exception e) {
        e.printStackTrace();
    }
    return newDate;
}
Alright answered 8/12, 2020 at 12:50 Comment(0)
J
1

If you want to parse it using straight JDK, i believe it should be parseable using the JAXB utils, see DatatypeFactory.newXMLGregorianCalendar or DatatypeConverter.parseDateTime.

Justifiable answered 28/12, 2010 at 1:4 Comment(0)
D
1

Use JodaTime

As a more concrete example to @Pangea's suggestion to use JodaTime, this is what you could use:

String timestamp = "2012-09-17T04:11:46Z";

DateTime date = ISODateTimeFormat.dateTimeParser().parseDateTime(timestamp);

This correctly recognizes the UTC timezone. I haven't tried it with milliseconds in the string timestamp, but I'm confident it'll work just as well.

Hope that helps others.

JP

Declaration answered 10/12, 2013 at 1:17 Comment(4)
FYI: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.Fustigate
@BasilBourque Thanks for pointing that out! If using Java SE 8+, they recommend moving over to java.time. Happy to see these improvements are being brought into the core.Declaration
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport. Further adapted for Android in the ThreeTenABP project.Fustigate
FYI, all these projects (Joda-Time, JSR 310, java.time classes, ThreeTen-Backport, and ThreeTen-Extra) are led by the same man, Stephen Colebourne.Fustigate
T
1

Two solutions:

  • OffsetDateTime (inbuilt in Java 8)
  • joda (the all mighty of dates - a 3rd party library)

OffsetDateTime is clearly a better option here, but if joda has been proven to be quite powerful from quite some time now and if someone prefers to use that then below code has sample of both

Code Sample of both approaches are given below:

public class Demo {
public static void jodaTimeStuff(String dateString, DateTimeZone dtz) {
    System.out.println(StringUtils.leftPad(dateString, 29, " ") + "\t------->\t" + ISODateTimeFormat.dateTime().parseDateTime(dateString).toDateTime(dtz));
    System.out.println(StringUtils.leftPad(dateString, 29, " ") + "\t------->\t" + OffsetDateTime.parse(dateString).toZonedDateTime());
}
public static void main(String[] args) throws Exception {
    jodaTimeStuff("2010-03-01T08:00:00.000Z", DateTimeZone.UTC);
    jodaTimeStuff("2010-03-01T08:00:00.000Z", DateTimeZone.forTimeZone(TimeZone.getTimeZone("Asia/Kolkata")));
    jodaTimeStuff("2010-03-01T00:00:00.000-08:00", DateTimeZone.UTC);
    jodaTimeStuff("2010-03-01T00:00:00.000-08:00", DateTimeZone.forTimeZone(TimeZone.getTimeZone("Asia/Kolkata")));
    jodaTimeStuff("2010-03-01T00:00:00.000+05:30", DateTimeZone.UTC);
    jodaTimeStuff("2010-03-01T00:00:00.000+05:30", DateTimeZone.forTimeZone(TimeZone.getTimeZone("Asia/Kolkata")));
    jodaTimeStuff("2021-11-15T02:27:24.540288Z", DateTimeZone.UTC);
    jodaTimeStuff("2021-11-15T02:27:24.540288Z", DateTimeZone.forTimeZone(TimeZone.getTimeZone("Asia/Kolkata")));
}

}

Output:

     2010-03-01T08:00:00.000Z   ------->    2010-03-01T08:00:00.000Z
     2010-03-01T08:00:00.000Z   ------->    2010-03-01T08:00Z
     2010-03-01T08:00:00.000Z   ------->    2010-03-01T13:30:00.000+05:30
     2010-03-01T08:00:00.000Z   ------->    2010-03-01T08:00Z
2010-03-01T00:00:00.000-08:00   ------->    2010-03-01T08:00:00.000Z
2010-03-01T00:00:00.000-08:00   ------->    2010-03-01T00:00-08:00
2010-03-01T00:00:00.000-08:00   ------->    2010-03-01T13:30:00.000+05:30
2010-03-01T00:00:00.000-08:00   ------->    2010-03-01T00:00-08:00
2010-03-01T00:00:00.000+05:30   ------->    2010-02-28T18:30:00.000Z
2010-03-01T00:00:00.000+05:30   ------->    2010-03-01T00:00+05:30
2010-03-01T00:00:00.000+05:30   ------->    2010-03-01T00:00:00.000+05:30
2010-03-01T00:00:00.000+05:30   ------->    2010-03-01T00:00+05:30
  2021-11-15T02:27:24.540288Z   ------->    2021-11-15T02:27:24.540Z
  2021-11-15T02:27:24.540288Z   ------->    2021-11-15T02:27:24.540288Z
  2021-11-15T02:27:24.540288Z   ------->    2021-11-15T07:57:24.540+05:30
  2021-11-15T02:27:24.540288Z   ------->    2021-11-15T02:27:24.540288Z

Some dependencies used in the sample code (one is just for formatting and another one is for joda:

    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.10.13</version>
    </dependency>

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.8</version>
    </dependency>

Dua me yaad rakhna (Please remember me in your prayers) 🙏🙏

Titer answered 18/12, 2021 at 5:38 Comment(0)
M
0

The question should be where requiredTimeStamp is coming from and in which format. Is it entered by a user, or read from another program? Which component creates the date in the String representation?

The format "2010-12-27T10:50:44.000-08:00" looks like standardized format ISO-8601 It should be parseable with the pattern yyyy-MM-dd'T'HH:mm:ss.SSSZ

Not sure which settings affect this, but there is an Oracle FAQ about Java TimeZones. It may be user.timezone system property or the /etc/localtime symlink in RHEL.

Mcgrody answered 28/12, 2010 at 0:9 Comment(1)
Sorry I was not clear. requiredTimeStamp is generated by a java application on the server (not ours) and sent as part of a service response. It seems to be using some default server setting since it changes with server reconfiguration. The timestamp '-08:00' is not parse-able by Z in the pattern even in an isolated unit test on my machine, Z can parse '-0800' or 'GMT-08:00' but not '-08:00'.Cassaundra
P
0

Try to change it to lower case z.

z processes most of the common general timezone syntax, while Z uses stricter RFC 822 time zone with 4 digits.

Although its documented that both should parse 'General timezone settings', it might make the difference in your case.

Pieplant answered 28/12, 2010 at 0:51 Comment(0)
M
0

SimpleDateFormat only accepts -0800 or GMT-08:00 as the timezone.

It seems the ISO 8601 format can not be parsed with SimpleDateFormat. Maybe you should have a look at Apache Commons Lang's FastDateFormat. It is compatible with SimpleDateFormat but accepts the ZZ pattern for the timezone that should parse the timezone format you need. DateFormatUtils contains some example constants that look like the pattern you need, just without the milliseconds (for example ISO_DATETIME_TIME_ZONE_FORMAT).

Margarethe answered 28/12, 2010 at 0:53 Comment(2)
As far as I could tell, FastDateFormat doesn't support parsing.Cassaundra
Seems you are right. Since it implements the standard Format interface I assumed that it would also parse the format like SimpleDateFormat. I didn't check the comments for the parse methods.Margarethe

© 2022 - 2024 — McMap. All rights reserved.