Javascript Date - set just the date, ignoring time?

Viewed 171460

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!!

8 Answers

var today = new Date();
var year = today.getFullYear();
var mes = today.getMonth()+1;
var dia = today.getDate();
var fecha =dia+"-"+mes+"-"+year;
console.log(fecha);

new Date().toISOString().split('T')[0]

let date = new Date((new Date("07/06/2012 13:30")).toDateString())
console.log(date)

Date handling is unavoidably tricky. First off, you will save a lot of trouble if you send datetimes as UTC ISO strings ("yyyy-MM-dd hh:mm:ss.000Z"). If you're storing dates as strings, store them as ISO strings. Parsing dates with slashes is locale dependent and so error prone. (Europeans put the day first, americans the month.)

To get a date string from a datetime ISO string, use myDatetimeString.substring(0,10). To get a date object from a date string, just add the zeros...

myUtcMidnightDateObject = new Date( myDateString + ' 00:00:00Z' )

To then format your UTC midnight date object, use toLocaleString() with the UTC option...

myFormattedDate = myUtcMidnightDateObject.toLocaleDateString({},{ timeZone: "UTC" })

Much more detail can be found here.

Just split the local date string to array by "/" and arrange them to accordingly,very simple.

var date=new Date();
var datearray=date.toLocaleString().split("/");
var sqldate= datearray[2].slice(0,4)+"-"+(datearray[0]<=9?"0"+datearray[0]:datearray[0])+"-"+(datearray[1]<=9?"0"+datearray[1]:datearray[1]);

If the date is in ISO string format, the date part can be seperated using

'2022-06-01T00:00:00'.split('T')[0]

result

2022-06-01
Related