Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Date - set just the date, ignoring time?

I have a bunch of objects, each of which has a timestamp, that I want to group by date, into a JSON object. The ultimate goal is something like this:

myObject = {     "06/07/2012" : [          {             "timestamp" : "07/06/2012 13:30",             ...         },         {             "timestamp" : "07/06/2012 14:00",             ...         }     ],     "07/07/2012 [...] } 

To get the date, I'm testing each timestamp object and using:

var visitDate = new Date(parseInt(item.timestamp, 10)); visitDate.setHours(0); visitDate.setMinutes(0); visitDate.setSeconds(0); 

..then I'm using that to store as a name for the JSON object. It seems messy, and I'm sure there should be an easier way of doing things.

Advice / suggestions welcomed!!

like image 305
Paul Avatar asked Aug 07 '12 14:08

Paul


People also ask

How do you compare dates without time?

To compare dates without time: Create a copy of each date. Use the setUTCHours() method to set the time on the copied dates to midnight. Compare the output from calling the getTime() method on the dates.

How do I create a specific date in JavaScript?

We can create a date object by passing the Date object a timestamp number in milliseconds. For example, new Date(1572840117245) . When we create a date object by passing it 0 milliseconds, it will return the date object for Jan 01 1970 05:30:00 .

Can JavaScript handle dates and time?

The date and time is broken up and printed in a way that we can understand as humans. JavaScript, however, understands the date based on a timestamp derived from Unix time, which is a value consisting of the number of milliseconds that have passed since midnight on January 1st, 1970.


2 Answers

How about .toDateString()?

Alternatively, use .getDate(), .getMonth(), and .getYear()?

In my mind, if you want to group things by date, you simply want to access the date, not set it. Through having some set way of accessing the date field, you can compare them and group them together, no?

Check out all the fun Date methods here: MDN Docs


Edit: If you want to keep it as a date object, just do this:

var newDate = new Date(oldDate.toDateString()); 

Date's constructor is pretty smart about parsing Strings (though not without a ton of caveats, but this should work pretty consistently), so taking the old Date and printing it to just the date without any time will result in the same effect you had in the original post.

like image 69
Nick Avatar answered Oct 04 '22 13:10

Nick


If you don't mind creating an extra date object, you could try:

var tempDate = new Date(parseInt(item.timestamp, 10)); var visitDate = new Date (tempDate.getUTCFullYear(), tempDate.getUTCMonth(), tempDate.getUTCDate()); 

I do something very similar to get a date of the current month without the time.

like image 33
James Tomasino Avatar answered Oct 04 '22 15:10

James Tomasino