Why does the first input work correctly, but the second input gives me a result for 5 hours ago?
new Date("2000-1-1")
Sat Jan 01 2000 00:00:00 GMT-0500 (EST)
new Date("2000-01-01")
Fri Dec 31 1999 19:00:00 GMT-0500 (EST)
how can i get the second one to cooperate with me?
var a = new Date("2000-1-1"); // Sat Jan 01 2000 00:00:00 GMT-0500 (EST)
var b = new Date("2000-01-01"); // Fri Dec 31 1999 19:00:00 GMT-0500 (EST)
console.log(a, a.getTime());
console.log(b, b.getTime());
parse(str) can read a date from a string. The string format should be: YYYY-MM-DDTHH:mm:ss. sssZ , where: YYYY-MM-DD – is the date: year-month-day.
The parse() method takes a date string (such as "2011-10-10T14:48:00" ) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the setTime() method and the Date object.
You can Convert the date value from String to Date in JavaScript using the `Date()`` class. You can also use parse, which is a static method of the Date class. You can also split the given string date into three parts representing the date, month, and year and then convert it to Date format.
The reason why you are seeing this is actually described on the Date.parse()
page of MDN (where a lot of the details around officially-supported Date
parameter formats are described). Specifically:
Differences in assumed time zone
Given a date string of "March 7, 2014", parse() assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC (ES5 and ECMAScript 2015). Therefore Date objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted.
So what you're seeing is a combination of two things:
As a result, you are seeing the U.S. Eastern Time zone version of midnight on January 1st, 2000, UTC time (or, 7 PM on December 31st, 1999).
Since your first example is using a non-standard format (from JS's point-of-view), the first assumption is not coming into play and the value is being created assuming the local timezone for the value (a browser-specific decision on how to handle a non-standard format).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With