Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a given date turns into a day before when using new Date()? [duplicate]

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?

like image 481
junerockwell Avatar asked Feb 04 '16 15:02

junerockwell


People also ask

Why a given Date turns into a day before when using new Date?

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.

Does new Date () Return current Date?

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.

What is difference between new Date () and Date now ()?

new Date() - creates a Date object representing the current date/time. Date. now() - returns the number of milliseconds since midnight 01 January, 1970 UTC.

What does new Date () mean?

new Date() : Creates a date object set to the current date and time.


1 Answers

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.

like image 86
Pointy Avatar answered Nov 14 '22 21:11

Pointy