TomJava
TomJava

Reputation: 529

Time in milliseconds when Timezone set as UTC from program

My computer timezone is IST and I m executing the following code

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
SimpleDateFormat format1 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
long millisFromDate = format1.parse("Tue, 22 Jun 2021 15:40:52 IST").getTime();
System.out.println(millisFromDate);

The above snippet prints 1624369252000.

Now when I convert 1624369252000 UTC time & date: Tue Jun 22 2021 13:40:52 in https://currentmillis.com/

I think I am doing something wrong. Can any one help?

It should have been 10:10:52 in UTC?

Upvotes: 2

Views: 979

Answers (1)

Anonymous
Anonymous

Reputation: 86148

Use java.time to specify what you mean by IST

I always recommend that you use java.time, the modern Java date and time API, for your date and time work.

Three letter time zone abbreviations like IST are very often, possibly most often ambiguous, so also very often give you different results from what you had expected. I suspect that this is also what happened in your case.

java.time gives us the opportunity to specify one or more preferred time zones in case of an ambiguous abbreviation. For example:

private static final Set<ZoneId> PREFERRED_ZONE = Set.of(ZoneId.of("Atlantic/Reykjavik"));

private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
        .appendPattern("EEE, dd MMM yyyy HH:mm:ss ")
        .appendZoneText(TextStyle.SHORT, PREFERRED_ZONE)
        .toFormatter(Locale.ROOT);

To use:

    String dateTimeString = "Tue, 22 Jun 2021 15:40:52 IST";
    ZonedDateTime zdt = ZonedDateTime.parse(dateTimeString, FORMATTER);
    System.out.println(zdt);

    long millisFromDate = zdt.toInstant().toEpochMilli();
    System.out.println(millisFromDate);

Output in this case:

2021-06-22T15:40:52Z[Atlantic/Reykjavik]
1624376452000

So just fill in the time zone ID that you intended in the first line. Other examples:

private static final Set<ZoneId> PREFERRED_ZONE = Set.of(ZoneId.of("Europe/Dublin"));
2021-06-22T15:40:52+01:00[Europe/Dublin]
1624372852000
private static final Set<ZoneId> PREFERRED_ZONE = Set.of(ZoneId.of("Asia/Tel_Aviv"));
2021-06-22T15:40:52+03:00[Asia/Tel_Aviv]
1624365652000

You had expected a result equivalent to 10:10:52 UTC. That you get from the following:

private static final Set<ZoneId> PREFERRED_ZONE = Set.of(ZoneId.of("Asia/Kolkata"));
2021-06-22T15:40:52+05:30[Asia/Kolkata]
1624356652000

A preferred zone of Asia/Colombo gives the same result.

Links

Upvotes: 3

Related Questions