Javascript Date - set just the date, ignoring time?

后端 未结 4 628
梦毁少年i
梦毁少年i 2021-02-06 23:58

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 =          


        
相关标签:
4条回答
  • 2021-02-07 00:04

    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.

    0 讨论(0)
  • 2021-02-07 00:04

    new Date((new Date("07/06/2012 13:30")).toDateString())

    0 讨论(0)
  • 2021-02-07 00:07

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

    0 讨论(0)
  • 2021-02-07 00:22

    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.

    0 讨论(0)
提交回复
热议问题