首页 > 解决方案 > 在时刻 js 中使用 'HH:mm' 字符串增加一小时(moment.js)

问题描述

我已经测试了这段代码:

a = '10:10'
console.log( moment( a ).subtract(1, 'h').format('HH:mm'));

但它不起作用,输出是:

Invalid date

控制台错误:

Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments: 
[0] _isAMomentObject: true, _isUTC: false, _useUTC: false, _l: undefined, _i: 10:10, _f: undefined, _strict: undefined, _locale: [object Object]

标签: javascriptmomentjs

解决方案


moment它不理解您提供给构造函数的时间格式。请指定时间格式作为第二个参数,您的代码应该运行。

我猜您使用的时间格式是HH:mm有意义的,小时格式为 24 小时格式,分钟格式:介于两者之间。

var a = '10:10'
var b = moment( a, 'HH:mm' ).subtract(1, 'h').format('HH:mm')
console.log(b);
alert(b);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>


推荐阅读