Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Date to milliseconds

I'm storing messages from an amazon cloud and ordering them by their timestamp in a sorted map.

I am parsing the timestamp from the cloud with the following code:

Date timestamp = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS'Z'", Locale.ENGLISH).parse(time);

and then I am storing in them in a sorted map with the key being the date. The issue is that the date only comes down to seconds precision. I can have several messages sent in 1 second, so I need them to be ordered with millisecond precision. Is there a data structure that allows this?

like image 620
Ben Flowers Avatar asked Jun 14 '12 10:06

Ben Flowers


People also ask

How do you convert date to milliseconds?

This is the number of seconds since the 1970 epoch. To convert seconds to milliseconds, you need to multiply the number of seconds by 1000. To convert a Date to milliseconds, you could just call timeIntervalSince1970 and multiply it by 1000 every time.

Does Java date have milliseconds?

The Date class in Java internally stores Date in milliseconds. So any date is the number of milliseconds passed since January 1, 1970, 00:00:00 GMT and the Date class provides a constructor which can be used to create Date from milliseconds.


2 Answers

Well as long as your source has a higher resolution than 1 second. Looks like that from the pattern, but you haven't shown us any input example.

Date is just a wrapper around a long milliseconds since 1970-01-01. So you have that already. Date.getTime() will return that, with millisecond precision.

Why would you think that Date only has one second precision? Date.compareTo(Date anotherDate) compares on a millisecond level. So your SortedMap should work fine unless you are doing something strange.

like image 156
Mattias Isegran Bergander Avatar answered Oct 01 '22 12:10

Mattias Isegran Bergander


I am not sure if you have done this, but you can create your own comparator and use that.

As a side note, depending on your applications setup you may want to be careful with how you use SimpleDateFormat, there are some issues with it.

like image 1
John Kane Avatar answered Oct 01 '22 12:10

John Kane