Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Convert given time and time zone to UTC time

I have a time with string type like: "2015-01-05 17:00" and ZoneId is "Australia/Sydney".

How can I convert this time information to the corresponding to UTC time using Java 8 datetime API?

Also need to considering DST stuff.

like image 681
ttt Avatar asked Jan 05 '16 06:01

ttt


People also ask

How do you convert timezone to UTC time?

(GMT-5:00) Eastern Time (US & Canada)Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.). Note The date also follows UTC format.

Is Java time instant UTC?

In java8, I would use the Instant class which is already in UTC and is convenient to work with. No, an Instant is not at local time. An Instant by definition is in UTC.

Is Java Util date UTC?

java. util. Date has no specific time zone, although its value is most commonly thought of in relation to UTC.


2 Answers

You are looking for ZonedDateTime class in Java8 - a complete date-time with time-zone and resolved offset from UTC/Greenwich. In terms of design, this class should be viewed primarily as the combination of a LocalDateTime and a ZoneId. The ZoneOffset is a vital, but secondary, piece of information, used to ensure that the class represents an instant, especially during a daylight savings overlap.

For example:

ZoneId australia = ZoneId.of("Australia/Sydney"); String str = "2015-01-05 17:00"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); LocalDateTime localtDateAndTime = LocalDateTime.parse(str, formatter); ZonedDateTime dateAndTimeInSydney = ZonedDateTime.of(localtDateAndTime, australia );  System.out.println("Current date and time in a particular timezone : " + dateAndTimeInSydney);  ZonedDateTime utcDate = dateAndTimeInSydney.withZoneSameInstant(ZoneOffset.UTC);  System.out.println("Current date and time in UTC : " + utcDate); 
like image 167
Mateusz Sroka Avatar answered Sep 23 '22 14:09

Mateusz Sroka


An alternative to the existing answer is to setup the formatter with the appropriate time zone:

String input = "2015-01-05 17:00";
ZoneId zone = ZoneId.of("Australia/Sydney");

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(zone);
ZonedDateTime utc = ZonedDateTime.parse(input, fmt).withZoneSameInstant(UTC);

Since you want to interact with a database, you may need a java.sql.Timestamp, in which case you don't need to explicitly convert to a UTC time but can use an Instant instead:

ZonedDateTime zdt = ZonedDateTime.parse(input, fmt);
Timestamp sqlTs = Timestamp.from(zdt.toInstant());
like image 25
assylias Avatar answered Sep 21 '22 14:09

assylias