简体   繁体   English

年份小于零时的日期差

[英]Date difference when year is smaller than zero

If I'm executing this: 如果我正在执行此操作:

var date = new Date("10.31");
date.setFullYear(-125);

the output of date is Sun Oct 31 -125 00:00:00 GMT+0200 (W. Europe Summer Time) date的输出为Sun Oct 31 -125 00:00:00 GMT+0200 (W. Europe Summer Time)

If I check this on wolframalpha the day seems to be tuesday. 如果我在wolframalpha上进行检查, 一天似乎是星期二。

Can someone explain why not the same day is displayed by both source? 有人可以解释为什么两个来源都不显示同一天吗?

The reason for the difference between JavaScript and wolframalpha website is that JavaScript is calculating the years mathematically, so it includes the year zero. JavaScript和wolframalpha网站之间存在差异的原因是JavaScript在数学上计算了年份,因此它包含了零年份。 Try to set the year to zero in JavaScript and you will see that it works. 尝试在JavaScript中将年份设置为零,您会发现它可以正常工作。 However, there is no such a thing as year zero, and the year before year 1 is year 1 BC. 但是,不存在零年,第一年之前的年份是公元前1年。 Try to set the year to zero on wolframalpha website and you get an error, while it automatically converts all negative years to years BC. 尝试在wolframalpha网站上将年份设置为零,您会得到一个错误,而它会自动将所有负年份转换为BC年。 This is the correct behavior. 这是正确的行为。

To get the BC years in JavaScript, add 1 to every year below 1. So year 0 becomes 1BC, and year -125 becomes 126BC. 要获得JavaScript的BC年,请在低于1的每年中加1。因此,0年变为1BC,而-125年变为126BC。 In JavaScript this gives you Sunday, and 126BC on wolframalpha website gives you Sunday too. 在JavaScript中,这为您提供星期日,而Wolframalpha网站上的126BC也为您提供星期日。 125BC gives you Tuesday on wolframalpha website, and -124 gives you the same in JavaScript. 125BC在wolframalpha网站上为您提供了星期二,-124在JavaScript中为您提供了同样的东西。

 var date = new Date(); date.setFullYear(-124); date.setMonth(9); date.setDate(31); console.log(date.toString()); date.setFullYear(-125); console.log(date.toString()); 

Javascript dates start in 1970. Javascript日期始于1970年。

Let's do a quick count. 让我们做个快速计数。

(new Date()).setYear(-125); //returns -66085584766591 (milliseconds from time 0)
//Let's convert those milliseconds in years...
//-66085584766591 = -2095,56 (years???)

As you can see, you can't rely on negative dates in Javascript. 如您所见,您不能依赖Javascript中的否定日期。

negative years in javascript do produce a BC date but it's kind of a poor design. javascript中的负数年份会产生BC日期,但这种设计不佳。 Wolfram Alpha is probably correct. Wolfram Alpha可能是正确的。 See this answer for more: Why does Date accept negative values? 有关更多信息,请参见此答案: 为什么Date接受负值?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM