Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round a timestamp to the nearest date

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?

like image 655
daGUY Avatar asked Dec 05 '14 20:12

daGUY


People also ask

How do I round a date in mysql?

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.

How do you round the date to the nearest hour?

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.


1 Answers

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);

like image 53
juvian Avatar answered Oct 13 '22 00:10

juvian