Javascript Date - set just the date, ignoring time?
Asked Answered
J

9

68

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

Jamille answered 7/8, 2012 at 14:8 Comment(4)
I can't imagine new Date(parseInt("07/06/2012 13:30",10)); would work. Or am I missing something?Blockish
Yeah, you're right - sorry, this is pasted out of some of my existing code and not proof-read! The current code stores the timestamp as the 'milliseconds from epoch' format, so it made more sense in its original context...Jamille
You should always store your dates with .toISOString() you're going to have issues with timezones storing dates with the strings you have. The only time you want to use that format is when you display it.Fray
You're correct @Fray - these days you should. When this question was written we still had to support IE8 which didn't support toISOString(). Hallelujah we live in a modern world now!Jamille
E
105

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.

Expansible answered 7/8, 2012 at 14:11 Comment(4)
Note: scroll down a bit to find the full list of methods. So many variants of toString, your head will pop.Expansible
That's probably a more sensible way to do it, I was thinking of leaving it as a Date object, although it's stored as text in JSON anyway I guess! The original reason for not using .toDateString() was being unsure about having spaces in the field. Don't suppose that matters though reallyJamille
ooh .valueOf() - that's also useful! Thanks!Jamille
Happy to help. If you like, I edited the question to give a way to keep them as Date objects, if it suits your fancyExpansible
H
25
new Date().toISOString().split('T')[0]
Humanitarianism answered 14/4, 2022 at 11:30 Comment(4)
This will provide the IST. not the local timeBorzoi
toISOString uses GMT/UTC, not local time. You get the wrong time, unless your timezone is actually GMT/UTC.Redoubtable
This is one the solid solution, like if you pass this to an endpoint that has validation its will surely success.Wright
Remember that including "toISOString()" will convert the time to UTC.Pectoral
M
11

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.

Mitre answered 7/8, 2012 at 14:16 Comment(1)
I think it should be getUTCDate. getUTCDay returns the day of the week (0,6). getUTCDate returns the day of the month (1,31)Affectionate
R
8

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);
Ruthieruthless answered 5/8, 2020 at 23:46 Comment(0)
D
3

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
Diaphony answered 27/6, 2022 at 12:43 Comment(0)
R
2

Since no good solution has been presented:

It actually depends on whether you want to achive 00:00:00.000 in UTC or LocalTime.
If you have a datetime-variable somedate (var somedate = new Date()), you can just do:

somedate.setHours(0, 0, 0, 0);

and somedate will now be 00:00:00.000.

If you want a new date that is 00:00:00.000 (and not modify the original-value), you do:

var nd = new Date(somedate.getTime());
nd.setHours(0, 0, 0, 0);

The above is for localtime.

Now, if you want the GMT-representation to be 00:00:00.000, you can do it like this:

var myDate = new Date(Date.parse("2023-11-30T23:59:59.000"));    
var timePortion = myDate.getTime() % 86400000;
var dateOnly = new Date(myDate - timePortion);

You could think, I'm very clever and doint it with the GMT-method for localtime, like:

var myDate = new Date(Date.parse("2023-11-30T23:59:59.000"));    
var timePortion = myDate.getTime() % 86400000;
var dateOnly = new Date(myDate - timePortion + myDate.getTimezoneOffset()*60000);

And think this works. But that would actually be stupid, because if you pass 2023-11-30T00:00:00.000", and your UTC/GMT-offset is less than zero, then you're off by about 24 hours, because the GMT will be 23:XX:YY.000 of the previous day, and that's the date that will be set to 00:00:00, meaning if you transform it to localtime, you get the wrong day.

Also, if you want to transform your newly time-cleared date into an iso-string (but in localtime) be aware that somedate.toISOString() will
A) be in GMT
and
B) it will have a Z at the end
, which is not ISO 8601, because ISO 8601-format is yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff and not yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'.

So if you need it as ISO-8601 in localtime, you can use this function:

    function removeTime(your_date)
    {
        var nd = new Date(your_date.getTime());
        nd.setHours(0, 0, 0, 0);

        function pad(number, num)
        {
            // Convert number to string
            var str = number.toString();

            // Calculate the number of zeroes to pad
            var zeroCount = num - str.length;

            // Pad with zeroes
            for (var i = 0; i < zeroCount; i++)
            {
                str = '0' + str;
            }

            return str;
        };

        return nd.getFullYear() +
            '-' + pad(nd.getMonth() + 1, 2) +
            '-' + pad(nd.getDate(), 2) +
            'T' + pad(nd.getHours(), 2) +
            ':' + pad(nd.getMinutes(), 2) +
            ':' + pad(nd.getSeconds(), 2) +
            '.' + pad(nd.getMilliseconds(), 3)
    };
Redoubtable answered 17/11, 2023 at 8:58 Comment(0)
K
1

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]);
Karlynkarma answered 18/1, 2022 at 15:11 Comment(0)
P
0

let date = new Date((new Date("07/06/2012 13:30")).toDateString())
console.log(date)
Philan answered 24/12, 2020 at 3:15 Comment(0)
J
0

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.

Jaffna answered 8/12, 2021 at 15:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.