开发者

How to tell if string time-A is before time-B?

开发者 https://www.devze.com 2022-12-30 12:41 出处:网络
if I have 4 variables startTime; endTime; startMerid; endMerid; startMarid and 开发者_开发知识库endMarid are either going to be \'AM\' or \'PM\'.

if I have 4 variables

startTime; endTime; startMerid; endMerid;

startMarid and 开发者_开发知识库endMarid are either going to be 'AM' or 'PM'.

but startTime and endTime are going to be strings like 'dd:dd'

so it may be start:12:30 PM and end:5:30 PM

How can I validate that the end time is not before the start time?

Thanks!!


You can use DateJS:

Date.parse('12:30pm') < Date.parse('5:30pm'); // true

EDIT:

Justin has a good point below. You can find the latest en-US version here

You can find the others in /trunk/build

EDIT 2016:

For those hitting this post in 2016+, it looks like a more up to date repo for DateJS is now at GitHub: https://github.com/datejs/Datejs

Also, it seems MomentJS is a very popular choice these days.


Parse out the hours and minutes fields so you have two separate variables. Then add 12 to hours if it is PM, unless the hour value is already 12. You can then compare the values directly:

if (startTimeHrs * 60 + startTimeMins) > 
   (  endTimeHrs * 60 + endTimeMins){ ... }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号