为什么转换时JavaScript中的日期不匹配?

时间:2018-11-05 16:26:21

标签: javascript momentjs

为什么javascript中的日期不匹配。我得到的毫秒数为“-2208988800000”。。我使用类似这样的时刻进行了转换

moment(new Date(-2208988800000).toUTCString()).format('DD-MMM-YYYY')

哪个输出为“ 1900年1月1日”(正确)?

现在我尝试再次获得相同的长值或毫秒

moment(new Date("01-Jan-1900")).format('x')
"-2209008070000"

为什么值不匹配? “ -2209008070000”和“ -2208988800000”不相同

2 个答案:

答案 0 :(得分:1)

new Date("01-Jan-1900")并非在所有浏览器中都适用。例如,Firefox输出Invalid DateDate构造函数有很多怪癖,这就是为什么您应该使用Moment.js之类的库来解析日期和时间字符串的原因。

有关其他详细信息,请参见MDN documentation on Date and new Date(dateString)

答案 1 :(得分:0)

  

我认为您在转换为DD-MMM-YYYY时会浪费很多时间

 console.log(moment(new Date(-2208988800000).toUTCString()).format('DD-MMM-YYYY HH:mm:ss'))

//output of above line is input to below.
console.log(moment.parseZone(new Date("31-Dec-1899 19:00:00")).format('x'))
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>