0

I am getting time form server in the following format:

"2016-12-13T03:03:49.572-08:00", this is not in UCT format. I need to convert it to my local time zone. If I add TimeZone.getTimeZone("America/Los_Angeles") explicitly and do the conversion than its happening well but i don't want to hard code like this as server location may change. Is there any way to convert the date in string format to UCT and then convert to local time zone? or how to convert to local time format for this specific case. (In JAVA)

s k
  • 101
  • 1
  • 5
  • See this http://stackoverflow.com/questions/22091107/get-date-object-in-utc-format-in-java. You can use TimeZone.getDefault() to obtain the local timezone – pringi Dec 13 '16 at 16:30
  • 3
    It's really unclear what you're asking here. What do you mean by "UCT format"? If you mean UTC rather than UCT, then you need to separate time zones (and offsets) from string formats - they're not the same. You can convert "2016-12-13T03:03:49.572-08:00" into a `Date` or `Instant` reasonably easily, then convert that into any time zone you want. – Jon Skeet Dec 13 '16 at 16:31
  • It is nice if you send date in https://en.wikipedia.org/wiki/ISO_8601 with timezone information then converting to LocalTimeZone is easier. OR do you get server time zone information as different source ? – Nagaraddi Dec 13 '16 at 16:37
  • Sorry its UTC, problem is if I use Date than it completely ignores time zone. Hence if I convert it to my local using TimeZone.getDefault() it will give incorrect result. Can you provide example for your approach? Thanks – s k Dec 13 '16 at 16:38
  • This is the only info i am getting from server no other info. – s k Dec 13 '16 at 16:39

2 Answers2

1

You can parse the String with this peace of code:

    Date d = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
            .parse("2016-12-13T03:03:49.572-08:00");

Then you can print the resulting date with this peace of code in the time Zone of the current VM (which is that of the "Server", if the code runs on the "Server"):

    System.out.println(
            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
                .format(d));

On my Computer the resulting Output is

2016-12-13T12:03:49.572+01:00

since I am living in Germany.

Of course you can do the Format of the Output as you like, if you Change the Format String for this. Read the class javadoc of SimpleDateFormat for this. E.g. you can use

    System.out.println(
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
                .format(d));

to get a more human readable Output.

If your code runs NOT on the Server, you somewhere have to know the timezone. You can then write e.g.

 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    format.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
    System.out.println(format.format(d));
Thomas Philipp
  • 261
  • 1
  • 5
  • FYI, the old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), and `java.text.SimpleTextFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. – Basil Bourque Dec 15 '16 at 07:37
1

tl;dr

OffsetDateTime.parse( "2016-12-13T03:03:49.572-08:00" )
              .toZoneSameInstant( ZoneId.of( "Pacific/Auckland" ) )

UTC

I'm guessing you meant UTC rather than UCT.

Offset vs zone

An offset-from-UTC is a number of hours & minutes & seconds. Example: -08:00 is eight hours behind UTC, such as seen on much of the west coast of North America (and elsewhere).

A time zone is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST). Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

You cannot deduce the zone from an offset. You can guess but that would be ill-advised. If you want to know the intended time zone, you must ask and be informed explicitly.

This is why the ZonedDateTime::toString method wisely extends the standard ISO 8601 format of YYYY-MM-DDTHH:MM:SS.S…Z to append the name of the zone in square brackets. For example, 2016-12-13T03:03:49.572-08:00[America/Los_Angeles].

OffsetDateTime & ZonedDateTime

Your input string lacks any info about zone, just offset. So we parse as an OffsetDateTime.

OffsetDateTime odt = OffsetDateTime.parse( "2016-12-13T03:03:49.572-08:00" );

If you want to see that in the wall-clock time of any particular zone, adjust.

ZoneId zLosAngeles = ZoneId.of( "America/Los_Angeles" );
ZonedDateTime zdtLosAngeles = odt.atZoneSameInstant( zLosAngeles );

You can adjust into any zone.

ZoneId zAuckland = ZoneId.of( "Pacific/Auckland" );
ZonedDateTime zdtAuckland = odt.atZoneSameInstant( zAuckland );

You can always extract the basic value in UTC, an Instant. All three of these toInstant calls result in the same value given the code above.

Instant instant = odt.toInstant();
Instant instant = zdtLosAngeles.toInstant();
Instant instant = zdtAuckland.toInstant();

Tips:

  • Usually best to work in UTC. Store and exchange data in UTC, and think in UTC. Think of UTC as “the One True Time”, all the offsets and zones are merely variations on the theme.
  • When serializing date-time values to text use the standard ISO 8601 formats. That is their purpose, and they are well designed: unambiguous, intuitive across cultures, and easy to parse.

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.

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android

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.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154