简体   繁体   中英

ZonedDateTime with timezone added to print format

I'm using https://github.com/JakeWharton/ThreeTenABP in my project.

I have org.threeten.bp

ZonedDateTime: 2019-07-25T 14:30:57+05:30 [Asia/Calcutta]

How can I get this printed with addition of the timezone hours? ie the result should have 2019-07-25T 20:00:57

Get the offset in the form of seconds from ZonedDateTime

ZonedDateTime time = ZonedDateTime.parse("2019-07-25T14:30:57+05:30");
long seconds = time.getOffset().getTotalSeconds();

Now get the LocalDateTime part from ZonedDateTime

LocalDateTime local = time.toLocalDateTime().plusSeconds(seconds);   //2019-07-25T20:00:57  

toLocalDateTime

Gets the LocalDateTime part of this date-time.

If you want to get the local date time in UTC use toInstant()

This returns an Instant representing the same point on the time-line as this date-time. The calculation combines the local date-time and offset.

Instant i = time.toInstant();   //2019-07-25T09:00:57Z

You misunderstood. The offset of +05:30 in your string means that 5 hours 30 minutes have already been added to the time compared to UTC. So adding them once more will not make any sense.

If you want to compensate for the offset, simply convert your date-time to UTC. For example:

    ZonedDateTime zdt = ZonedDateTime.parse("2019-07-25T14:30:57+05:30[Asia/Calcutta]");
    OffsetDateTime utcDateTime = zdt.toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC);
    System.out.println(utcDateTime);

Output:

2019-07-25T09:00:57Z

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM