Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

javascript - Comparing two times with 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???

Fiddle: http://jsfiddle.net/KyleMuir/M4R4z/

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...