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)
};
new Date(parseInt("07/06/2012 13:30",10));
would work. Or am I missing something? – Blockish.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. – FraytoISOString()
. Hallelujah we live in a modern world now! – Jamille