[英]Moment js Time Ago calculate wrong date
maybe a simple question but i don't get it. 也许是一个简单的问题,但我不明白。
var date = new Date();
test = date.toISOString();
alert(moment(test, "YYYYMMDD").fromNow());
Will return "16 hours", but why? 将返回“ 16小时”,但是为什么呢?
Demo: https://jsfiddle.net/5jacaxbf/ 演示: https : //jsfiddle.net/5jacaxbf/
Because you are using moment(String, String)
, instead of moment(String)
( toISOString()
output is obviously in ISO 8601 format) or moment(Date)
. 因为您使用的是moment(String, String)
而不是moment(String)
( toISOString()
输出显然是ISO 8601格式)或moment(Date)
。
So moment(test, "YYYYMMDD")
will be the start of the day instead of the current time. 因此, moment(test, "YYYYMMDD")
将是一天的开始,而不是当前时间。
As the Default section states: 如“ 默认”部分所述:
You can create a moment object specifying only some of the units, and the rest will be defaulted to the current day, month or year, or 0 for hours, minutes, seconds and milliseconds. 您可以创建一个矩对象,仅指定某些单位,其余的将默认为当前日期,月份或年份,或者小时,分钟,秒和毫秒的默认值为0。
var date = new Date(); test = date.toISOString(); var m1 = moment(test, "YYYYMMDD") console.log(m1.format()); console.log(m1.fromNow()); var m2 = moment(test) console.log(m2.format()); console.log(m2.fromNow()); var m3 = moment(date) console.log(m3.format()); console.log(m3.fromNow());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.