问题描述
我有一个问题需要我以12小时的格式进行两次比较并且比较它们,我们的项目中包含了moment.js,我们最初认为它会像这样微不足道:
I have a problem that requires me to take two times in 12 hour format and compare them, we have moment.js included in our project and we initially thought it would be as trivial as this:
var beginningTime = moment('8:45am');
var endTime = moment('9:00am');
console.log(beginningTime.isBefore(endTime)); //false???
小提琴:
我们缺少什么?感觉这应该不是一个难以解决的难题。当我们在 beginningTime
或 endTime
上执行任何时刻函数时,它只是说 NAN
Is there something we are missing? It feels like this shouldn't be a hard problem to solve. When we perform any moment functions on our beginningTime
or endTime
it simply says NAN
推荐答案
如果你总是处理中的时间h:mma
格式,您可以在解析时指定它...
If you are always dealing with the time in h:mma
format, you can specify it when parsing...
var beginningTime = moment('8:45am', 'h:mma');
var endTime = moment('9:00am', 'h:mma');
console.log(beginningTime.isBefore(endTime)); // true
console.log(beginningTime.toDate()); // Mon May 12 2014 08:45:00
console.log(endTime.toDate()); // Mon May 12 2014 09:00:00
<script src="https://cdn.jsdelivr.net/momentjs/2.13.0/moment.min.js"></script>
它将使用今天作为日期,因此如果您跨越不同的日期,它将无效。
It will use today as the date, so it won't work if you are spanning different days.
这篇关于用Moment JS比较两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!