Moment js Time Ago 计算错误的日期
Moment js Time Ago calculate wrong date
也许是一个简单的问题,但我不明白。
var date = new Date();
test = date.toISOString();
alert(moment(test, "YYYYMMDD").fromNow());
会return“16小时”,但为什么?
因为您正在使用 moment(String, String)
, instead of moment(String)
(toISOString()
output is obviously in ISO 8601 format) or moment(Date)
.
所以 moment(test, "YYYYMMDD")
将是一天的开始而不是当前时间。
如 Default 部分所述:
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.
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>
也许是一个简单的问题,但我不明白。
var date = new Date();
test = date.toISOString();
alert(moment(test, "YYYYMMDD").fromNow());
会return“16小时”,但为什么?
因为您正在使用 moment(String, String)
, instead of moment(String)
(toISOString()
output is obviously in ISO 8601 format) or moment(Date)
.
所以 moment(test, "YYYYMMDD")
将是一天的开始而不是当前时间。
如 Default 部分所述:
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.
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>