Seagull
Seagull

Reputation: 2299

Converting a time to milliseconds correctly in java.time (Java 8)

I've been trying to convert a "DateTime" to milliseconds using the java.time package built into Java 8.

But I haven't been able to do it correctly. I am trying to convert "29/Jan/2015:18:00:00" to milliseconds. The following is something I tried

Instant instant = Instant.parse("2015-01-29T18:00:00.0z");
Long instantMilliSeconds = Long.parseLong(instant.getEpochSecond() + "" + instant.get(ChronoField.MILLI_OF_SECOND));
System.out.println(new Date(instantMilliSeconds)); // prints Sun Jun 14 05:06:00 PDT 1970

I tried using LocalDateTime, but couldn't find a way to effectively do the conversion to milliseconds. I am not saying this is the best way to do this, if you know something better, I would really appreciate some pointers.

Upvotes: 27

Views: 59737

Answers (3)

Jeffrey
Jeffrey

Reputation: 44808

You should use Instant::toEpochMilli.


System.out.println(instant.toEpochMilli());
System.out.println(instant.getEpochSecond());
System.out.println(instant.get(ChronoField.MILLI_OF_SECOND));

prints

1422554400000
1422554400
0

Your version did not work because you forgot to pad instant.get(ChronoField.MILLI_OF_SECOND) with extra zeros to fill it out to 3 places.

Upvotes: 50

Seagull
Seagull

Reputation: 2299

Okay, I think I finally found an easy way to do what I am trying to do

LocalDateTime localDateTime = LocalDateTime.parse(date, DateTimeFormatter.ofPattern("dd/MMM/uuuu:H:m:s"));
System.out.println(localDateTime.toInstant(ZoneOffset.UTC).toEpochMilli());

Prints 1390903200000

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347204

From Date and Time Classes the tutorials...

DateTimeFormatter formatter
                    = DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss");
LocalDateTime date = LocalDateTime.parse("29/Jan/2015:18:00:00", formatter);
System.out.printf("%s%n", date);

Prints 2015-01-29T18:00

ZoneId id = ZoneId.systemDefault();
ZonedDateTime zdt = ZonedDateTime.of(date, id);
System.out.println(zdt.toInstant().toEpochMilli());

Prints 1422514800000

Upvotes: 3

Related Questions