I have an ArrayList of Timestamps. I want to split this ArrayList into several ArrayLists ad put them into a HashMap grouped by the day. So all the Timestamps for 14-01-2011 go together, all the Timestamps for 29-01-2012 go together, etc…
Pseudocode –
myTimestampMap['21-03-2012'] = ArrayList { myTimestamp[0], myTimestamp[1], myTimestamp[2] };
myTimestampMap['22-03-2012'] = ArrayList { timeStmyTimestamp[3], myTimestamp[4]};
I know the following algorithm will work –
-
Take the first value in the Timestamps ArrayList, find it’s ‘day’ and assign that to a variable called currentDay (so if the first Timestamp is 12 March 2012 14:26PM, assign 12 March 2012 00:00AM to currentDay).
-
Now iterate over the Timestamps and if getDay() is not within currentDay + 24 hours, assign currentDay = getDay() (at 00:00AM), create a new key in the HashMap and put all the following Timestamps in it until we come to a Timestamp where again getDay() is not within currentDay + 24 hours, then just repeat.
- The thing I am unsure of is if I have a Timestamp that signifies, say, 12 March 2012 16:57PM, I have to derive a Timestamp (currentDay) from that that signifies 12 March 2012 00:00AM. How would I do that?
- I also need to then check if a given Timestamp is within 24 hours of the currentDay Timestamp. How would I do that?
Assuming that you can ignore time zone issues (e.g. all the times you have are in UTC and you don’t mind leap seconds!)…
If you convert the date and time into a number of seconds since some reference date (epoch time format uses
1/1/1970 00:00:00), then you can just do seconds integer divided by the number of seconds in a day) to convert it to an integer representing the number of days.To check if a given time stamp is in the same day then you’d simply compare the values
/ 86400.