I need to group a bunch of items in my web app by date created.
Each item has an exact timestamp, e.g. 1417628530199
. I'm using Moment.js and its "time from now" feature to convert these raw timestamps into nice readable dates, e.g. 2 Days Ago
. I then want to use the readable date as a header for a group of items created on the same date.
The problem is that the raw timestamps are too specific - two items that are created on the same date but a minute apart will each have a unique timestamp. So I get a header for 2 Days Ago
with the first item underneath, then another header for 2 Days Ago
with the second item underneath, etc.
What's the best way to round the raw timestamps to the nearest date, so that any items created on the same date will have the exact same timestamp and thus can be grouped together?
This should work and is pretty fast.
This worked for my project. Pure math, no string manipulation needed, no external lib needed, so it's super fast.
You can try by copying the above function to javascript console and then do
normalizeTimeToDate(Date.now())
Well, using js you can do:
Edit:
After checking several methods, this one seems to be the faster:
You can check difference in speed here: http://jsfiddle.net/juvian/3aqmhn2h/
Just construct a new Date from the existing one using only the year, month, and date.
Since this seems to have a small footprint, it can also be useful to extend the prototype to include it in the Date "class".
Minimized:
Try this:
http://jsfiddle.net/cdn5rvck/4/
Using Moment.js, you can use the following code to round everything to the beginning of the day:
You can read more about
startOf()
in the docs.