date js 减去_为什么js以某种格式从Date对象中减去一天?

I get dates from the database in this format:

yyyy-mm-dd

When I create a javascript Date object using this string, it builds a day before the date.

You can test this in your console:

var d = new Date("2015-02-01");

d

You will get January 31st! I've tested many theories, but none answer the question.

The day is not zero-based, otherwise it would give Feb 00, not Jan 31

It's not performing a math equation, subtracting the day from the month and/or year

Date(2015-02-01) = Wed Dec 31 1969

Date("2015-01") = Wed Dec 31 2014

It is not confusing the day for the month

Date("2015-08-02") = Sat Aug 01 2015

If this were true the date would be Feb 08 2015

If you create a Date using a different format, it works fine

Date("02/01/2015") = Feb 1st, 2015

My conclusion is that js does this purposefully. I have tried researching 'why' but can't find an explanation. Why does js build dates this way, but only with this format? Is there a way around it, or do I have to build the Date, then set it to the next day?

PS: "How to change the format of the date from the db" is not what I'm asking, and that is why I'm not putting any db info here.

解决方案

Some browsers parse a partial date string as UTC and some as a local time,

so when you read it the localized time may differ from one browser to another

by the time zone offset.

You can force the Date to be UTC and add the local offset if you

want the time to be guaranteed local:

1. set UTC time:

var D= new Date("2015-02-01"+'T00:00:00Z');

2. adjust for local:

D.setMinutes(D.getMinutes()+D.getTimezoneOffset());

value of D: (local Date)

Sun Feb 01 2015 00:00:00 GMT-0500 (Eastern Standard Time)

Offset will be whatever is local time.

Some differences between browsers when time zone is not specified in a parsed string:

(tested on Eastern Standard Time location)

(new Date("2015-02-01T00:00:00")).toUTCString();

Firefox 35: Sun, 01 Feb 2015 05:00:00 GMT

Chrome 40: Sun, 01 Feb 2015 00:00:00 GMT

Opera 27: Sun, 01 Feb 2015 00:00:00 GMT

IE 11: Sun, 01 Feb 2015 05:00:00 GMT

IE and Firefox set the Date as if it was local, Chrome and Opera as if it was UTC.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值