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?
Here is the SQL query to round current timestamp to seconds. mysql> SELECT date_format(order_date,'%Y-%m-%d %H:%i:%s') from sales; As you can see, it is very easy to change datetime and timestamp values to month, day, hour, minute and second.
To round a date to the nearest hour:If adding 30 minutes to the date rolls over to the next hour, the hour is rounded up, otherwise down.
Well, using js you can do:
var d = new Date(1417628530199);
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
A shorter way of writing it is d.setHours(0, 0, 0, 0);
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