The given date is 2016-02-04
. That's suppose to be Feb. 4, 2016. But when I use new Date()
, it returns as Wed Feb 03 2016 16:00:00 GMT-0800 (PST)
and not Thu Feb 04...
.
Below is all I literally do:
var _entryDate = new Date("2016-02-04");
console.log(_entryDate); // Wed Feb 03 2016 16:00:00 GMT-0800 (PST)
Why is this happening and how do I get my desired result which is Feb. 4 and not the day before that?
The format you're using is interpreted as being a UTC date, so the time is assumed to be midnight in Western Europe. That's 8 hours ahead of you. You can force the time zone to be interpreted by tacking on T00:00-0800 to the date string.
In JavaScript, we can easily get the current date or time by using the new Date() object. By default, it uses our browser's time zone and displays the date as a full text string, such as "Fri Jun 17 2022 10:54:59 GMT+0100 (British Summer Time)" that contains the current date, time, and time zone.
new Date() - creates a Date object representing the current date/time. Date. now() - returns the number of milliseconds since midnight 01 January, 1970 UTC.
new Date() : Creates a date object set to the current date and time.
The format you're using is interpreted as being a UTC date, so the time is assumed to be midnight in Western Europe. That's 8 hours ahead of you.
You can force the time zone to be interpreted by tacking on T00:00-0800
to the date string. It might be more robust for you to parse the date yourself and construct your Date instance with numeric year, month, and date parameters.
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