momentjs subtract返回相同的值

时间:2017-11-07 18:24:40

标签: javascript momentjs

我正在将时间值从1256格式解析为HHmm:

let parsedTime = moment(time, "HHmm");
console.log(parsedTime)
//moment("2017-11-07T12:56:00.000") 


console.log(parsedTime.subtract(3, 'hours'))
//moment("2017-11-07T12:56:00.000")

我做错了什么?

2 个答案:

答案 0 :(得分:1)

我猜你正在观察具有属性_i的时刻对象,它告诉你初始值。使用format

可以看到实际值

let time = moment("1256", "HHmm");
console.log(time.format())
//moment("2017-11-07T12:56:00.000")


console.log(time.subtract(3, 'hours').format())
//moment("2017-11-07T9:56:00.000")
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>

答案 1 :(得分:1)

如果您在控制台中观察到返回对象的_d属性,它将在减法后保留修改后的值。

let time = '1256';
let parsedTime = moment(time, "HHmm");
console.log(parsedTime)
/* Object 
 { _isAMomentObject: true, _i: "1256", _f: "HHmm", _isUTC: false, _pf: Object, _locale: Object, _d: Date 2017-11-08T07:26:00.000Z, _isValid: true } */


console.log(parsedTime.subtract(3, 'hours'));

/* Object { _isAMomentObject: true, _i: "1256", _f: "HHmm", _isUTC: false, _pf: Object, _locale: Object, _d: Date 2017-11-08T04:26:00.000Z, _isValid: true } */