-2

I want to convert a timestamp in UTC, e.g. May 27, 2020, 22:35 (UTC) to epoch seconds. I will be hard coding the time in my code, so don't need to parse any string. I am using the Calendar class as follows:

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.set(2020, Calendar.MAY, 22, 22, 35);
calendar.getTimeInMillis();

The epoch time is correct to the second level, but the milliseconds part seems random on every run. Example run output:

Time : 1590618900110

Is there a way I can set the millisecond to zero in Calendar object, or a better option, possibly from the java.time framework?

Edit:

The following worked fine for me, since I am hardcoding the UTC time in code:

Instant instant = Instant.parse("2020-05-27T22:35:00.00Z");
long timeInMillisEpoch = instant.toEpochMilli();

Thank you, Ahmed.

Ahmed A
  • 3,362
  • 7
  • 39
  • 57

1 Answers1

2

since you already know the "exact datetime" and I guess you want to avoid the parsing, you can use this .of() method from java.time.OffsetDateTime, e.g.:

$ jshell

jshell> import java.time.*

jshell> OffsetDateTime odt = OffsetDateTime.of(2020, 5, 27, 22, 35, 0, 0, ZoneOffset.UTC)
odt ==> 2020-05-27T22:35Z

jshell> odt.toEpochSecond()
$14 ==> 1590618900

jshell> odt.toInstant().toEpochMilli()
$19 ==> 1590618900000

edit: rewrite following @Andreas advices

MarcoLucidi
  • 2,007
  • 1
  • 5
  • 8
  • 2
    Use constant [`ZoneOffset.UTC`](https://docs.oracle.com/javase/8/docs/api/java/time/ZoneOffset.html#UTC) instead of `ZoneId.of("UTC")`, which also means you should use [`OffsetDateTime`](https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html) instead of [`ZonedDateTime`](https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html). – Andreas May 27 '20 at 17:34
  • 2
    Question is asking for "epoch time (**seconds**)", so use [`offsetDateTime.toEpochSecond()`](https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html#toEpochSecond--). No need to create an `Instant` first. – Andreas May 27 '20 at 17:36
  • @Andreas it is not very clear if he wants seconds (title) or milliseconds (question body) so I left both examples – MarcoLucidi May 27 '20 at 17:54