Home > Mobile >  How to convert joda DateTime with timezone to DateTime with same time in UTC?
How to convert joda DateTime with timezone to DateTime with same time in UTC?

Time:09-13

I have such input date:

DateTime date = new DateTime("2022-10-30T00:00:00.000 11:00");

How can I convert it to UTC while keeping the same time:"2022-10-30 00:00:00.000"?

In other words, I want the date.getMillis(); method to return the midnight of "2022-10-30" in UTC.

For now, if I call date.getMillis();, I get "2020-10-29" in UTC.

CodePudding user response:

I'm not sure you're doing what you think you're doing here.

The date you're creating doesn't have a UTC 11 offset, it's in your JVM's default time zone (demo):

System.out.println(DateTimeZone.getDefault());
DateTime date = new DateTime("2022-10-30T00:00:00.000 11:00");
System.out.println(date);

prints

Etc/UTC
2022-10-29T13:00:00.000Z

so the local date portion of this is 2022-10-29.

If you want to create it with the specified offset, you have to either use DateTime.parse:

DateTime date = DateTime.parse("2022-10-30T00:00:00.000 11:00");

or specify it:

DateTime date = new DateTime("2022-10-30T00:00:00.000 11:00", DateTimeZone.forOffsetHours(11));

Printing either of these results in:

2022-10-30T00:00:00.000 11:00

Now, date.withZoneRetainFields(DateTimeZone.UTC) is:

2022-10-30T00:00:00.000Z

as required.

  • Related