简体   繁体   English

现在数据中moment.js错误

[英]moment.js error in data now

I have this code: 我有以下代码:

 var utc = moment.tz(1521221491000, "UTC"); var local = utc.clone().tz(moment.tz.guess()); console.log(moment([2018, 03, 15]).fromNow()); console.log('moment() piece by piece: ' + moment().get('year') + ' ' + moment().get('month') + ' ' + moment().get('date') + '. Data inside of momment: ' + moment().format()); console.log(local.format("YYYY-MM-DD HH:MM:SS")); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data.js"></script> 

In the line 3 在第3行

console.log(moment([2018, 03, 15]).fromNow()); console.log(moment([2018,03,15])。fromNow());

Suppose to say '1 day ago', at the moment to write this question is 16 of March 2018... And for some reason the response is 假设说“ 1天前”,目前写此问题的时间是2018年3月16日...由于某种原因,答复是

in a month... 在一个月...

Any idea why this error, the error is in the month var. 任何想法为什么会出现此错误,该错误在月份var中。

Moment使用与JavaScript Date对象相同的(讨厌的)日期系统,其中January = 0,February = 1,依此类推。因此3表示April,这是从现在开始的一个月。

As indicated in moment's documentation , when parsing an array as the argument, moment mirrors the native javascript Date object's 0-based indexing for months. 如moment的文档中所述 ,当解析数组作为参数时,moment会在几个月内镜像本地javascript Date对象基于0的索引。 So 3 is, confusingly, April. 令人困惑的是,3月是4月。

I personally find it's much easier to have moment parse pre-formatted string or objects, though your mileage may vary. 我个人发现,时刻分析预格式化的字符串或对象要容易得多,尽管里程可能会有所不同。

Like answered by Gnagy in this thread ( https://stackoverflow.com/a/20094956/8733102 ), 就像Gnagy在此线程( https://stackoverflow.com/a/20094956/8733102 )中回答的那样,

According to the documentation , months are zero indexed. 根据文档 ,月份是零索引的。 So January is 0 and December is 11. 因此,一月是0,十二月是11。

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

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