Reputation: 2034
I set a Date string to milliseconds to start from midnight like:
var date = new Date("2017-12-14").setUTCHours(0,0,0,0)
Now the date = 1513209600000; i.e., Thu Dec 14 2017 00:00:00. This is exactly how I want to start my date from midnight or start of the day, i.e., midnight.
But when I'm trying to convert this timestamp to again in Date object, it is not retaining the hour format, like:
var dateObj = new Date(date); // Thu Dec 14 2017 05:30:00 GMT+0530 (IST)
I want this dateObj to have the date and time to start from midnight. Can anyone please suggest what exactly I am doing wrong here? Thanks in advance.
Upvotes: 1
Views: 1421
Reputation: 147383
Per EMCA-262, a date string in ISO 8601 format like "2017-12-14" will be parsed by the built-in parser as UTC (contrary to ISO 8601) and the time will be set to 00:00:00 UTC so there is not need to zero the hours.
So in:
var date = new Date("2017-12-14").setUTCHours(0,0,0,0)
the setUTCHours call is redundant.
Since you are +05:30, then for the period from local midnight to 05:30, the UTC date will be the previous day.
If you want to parse "2017-12-14" as a local date with the time set to 00:00:00, then you can either:
For case 1:
function parseISOLocal(s) {
var b = s.split(/\D/);
return new Date(b[0], --b[1], b[2]);
}
var s = "2017-12-14";
console.log(parseISOLocal(s).toString());
For case 2:
var s = "2017-12-14";
// Parsed as UTC
var d = new Date(s);
// Adjust for host timezone
d.setUTCMinutes(d.getUTCMinutes() + d.getTimezoneOffset());
// Show local date
console.log(d.toString());
Upvotes: 0
Reputation: 9
I think use should change setUTCHours to setHours
var date = new Date("2017-12-14").setHours(0,0,0,0)
Upvotes: 0
Reputation: 15351
The date object is retaining its value, what you see is your browser's representation of that date in the local time zone. Try dateObj.toUTCString()
to read the original value.
Upvotes: 3