Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading