nullUser
nullUser

Reputation: 1169

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-25T14: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-25T20:00:57

Upvotes: 2

Views: 797

Answers (2)

Anonymous
Anonymous

Reputation: 86324

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

Upvotes: 2

Ryuzaki L
Ryuzaki L

Reputation: 40078

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

Upvotes: 2

Related Questions