admin管理员组

文章数量:1410731

I need to convert a String to a Date object.

The date string is delivered in the following format:

"2015-01-28T00:00:00"

When I create a new Date, I get the previous date:

Entered: new Date("2015-01-28T00:00:00")

Result: Tue Jan 27 2015 17:00:00 GMT-0700 (Mountain Standard Time)

Does anyone know why this is occurring?

I need to convert a String to a Date object.

The date string is delivered in the following format:

"2015-01-28T00:00:00"

When I create a new Date, I get the previous date:

Entered: new Date("2015-01-28T00:00:00")

Result: Tue Jan 27 2015 17:00:00 GMT-0700 (Mountain Standard Time)

Does anyone know why this is occurring?

Share Improve this question asked Feb 20, 2015 at 17:25 Philip RaathPhilip Raath 4885 silver badges18 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 5

When you enter the following:

 new Date("2015-01-28T00:00:00");
 // Result: Tue Jan 27 2015 17:00:00 GMT-0700 (Mountain Standard Time)

the browser assumes that you are giving a date in GMT Time zone. So it will automatically convert the given date to your local date.

It's always a good idea to inform the browser of the timezone you are working on in order to prevent future problems:

 new Date("2015-01-28T00:00:00-07:00");
 // Result: Tue Jan 28 2015 00:00:00 GMT-0700 (Mountain Standard Time)

Actually, you aren't getting the previous date . . . you are getting that date, offset by the timezone difference.

Tue Jan 27 2015 17:00:00(Mountain Time) + 7 hours (time zone difference) = 2015-01-28T00:00:00 (GMT)

Or, in English, when it is 12:00 Midnight in Greenwich, England, it is 5:00 PM on the previous day in Denver, Colorado. ;)

It's the right date/time, just in a different timezone.

本文标签: Why is new Date() subtracting 1 day in JavascriptStack Overflow