Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZonedDateTime to UTC with offset applied?

I am using Java 8
This is what my ZonedDateTime looks like

2013-07-10T02:52:49+12:00

I get this value as

z1.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)

where z1 is a ZonedDateTime.

I wanted to convert this value as 2013-07-10T14:52:49

How can I do that?

like image 860
daydreamer Avatar asked Feb 28 '16 22:02

daydreamer


People also ask

Is ZonedDateTime a UTC?

A ZonedDateTime represents a date-time with a time offset and/or a time zone in the ISO-8601 calendar system. On its own, ZonedDateTime only supports specifying time offsets such as UTC or UTC+02:00 , plus the SYSTEM time zone ID.

What is offset in ZonedDateTime?

ZoneOffset describes a time-zone offset, which is the amount of time (typically in hours) by which a time zone differs from UTC/Greenwich. ZonedDateTime describes a date-time with a time zone in the ISO-8601 calendar system (such as 2007-12-03T10:15:30+01:00 Europe/Paris ).

How do I convert ZonedDateTime to another timezone?

Changing Timezones of ZonedDateTime To convert a ZonedDateTime instance from one timezone to another, follow the two steps: Create ZonedDateTime in 1st timezone. You may already have it in your application. Convert the first ZonedDateTime in second timezone using withZoneSameInstant() method.

Should I use ZonedDateTime or OffsetDateTime?

Use OffsetDateTime to store unique instants in the universal timelines irrespective of the timezones, such as keeping the timestamps in the database or transferring information to remote systems worldwide. Use ZonedDateTime for displaying timestamps to users according to their local timezone rules and offsets.


2 Answers

Is this what you want? This converts your ZonedDateTime to a LocalDateTime with a given ZoneId by converting your ZonedDateTime to an Instant before.

LocalDateTime localDateTime = LocalDateTime.ofInstant(z1.toInstant(), ZoneOffset.UTC);

Or maybe you want the users system-timezone instead of hardcoded UTC:

LocalDateTime localDateTime = LocalDateTime.ofInstant(z1.toInstant(), ZoneId.systemDefault());
like image 93
SimMac Avatar answered Oct 13 '22 09:10

SimMac


It looks like you need to convert to the desired time zone (UTC) before sending it to the formatter.

z1.withZoneSameInstant( ZoneId.of("UTC") )
  .format( DateTimeFormatter.ISO_OFFSET_DATE_TIME )

should give you something like 2018-08-28T17:41:38.213Z

like image 26
DaveTPhD Avatar answered Oct 13 '22 09:10

DaveTPhD