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.
A simple solution is to get the timedelta object by finding the difference of the given datetime with Epoch time, i.e., midnight 1 January 1970. To obtain time in milliseconds, you can use the timedelta. total_seconds() * 1000 .
Here's an example of what you want/need to do (assuming time zone is not involved here): String myDate = "2014/10/29 18:10:45"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = sdf. parse(myDate); long millis = date. getTime();
1 minute = 60 * seconds, 1 second = 1000 millis => 1 minute = 60000 millis. This is basic math! getTimeInMillis() returns the current time as UTC milliseconds from the epoch.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With