为什么js以某种格式从Date对象中减去一天? [英] Why does js subtract a day from a Date object with a certain format?

查看:219
本文介绍了为什么js以某种格式从Date对象中减去一天?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以这种格式从数据库获取日期:

I get dates from the database in this format:


yyyy-mm-dd

yyyy-mm-dd

当我使用此字符串创建一个JavaScript Date对象时,它会在日期之前建立一个日期。

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

您将获得1月31日!我已经测试了很多理论,但是没有人回答这个问题。

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


  • 这一天不是以零为基础的,否则会给予二00 00,不是1月31日

  • 不执行数学方程,减去月份和/或年份的日子

    • 日期(2015-02 -01)= Wed Dec 31 1969

    • 日期(2015-01)= Wed Dec 31 2014


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

    • 如果这是真的,日期为2015年2月8日


    • 日期(02/01/2015)= 2015年2月1日

    我的结论是js有目的地这样做。我试过研究为什么,但找不到解释。 为什么js以这种方式构建日期,但只能使用此格式?有没有办法,或者我必须构建日期,然后将其设置为第二天?

    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:如何从数据库更改日期格式不是我所要求的,这就是为什么我没有在这里提供任何数据库信息。

    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.

    推荐答案

    某些浏览器会将UTC的部分日期字符串解析为部分日期字符串,并将某些作为本地时间解析。

    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

    按时区偏移。

    您可以强制日期为UTC,如果您

    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());
    

    D值(本地日期)
    Sun Feb 01 2015 00: 00:00 GMT-0500(东部标准时间)

    value of D: (local Date) Sun Feb 01 2015 00:00:00 GMT-0500 (Eastern Standard Time)

    em>

    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. 
    

    这篇关于为什么js以某种格式从Date对象中减去一天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆