Reputation: 6805
I've seen a few different questions on here regarding finding the difference between using two different dates.
My question is similar to Parse ONLY a time string with DateJS.
I basically have 2 time inputs:
<input id="start_time" type="text">
<input id="end_time" type="text">
The format of these will always be: 07:15 AM
or 08:30 AM
Essentially, what I am trying to do is ensure the start_time
is not greater than the end_time
.
I have tried using DateJS to parse the date, but it returns null
:
Date.parseExact("03:15 PM", "HH:mm"); <--- returns null
How should I go about comparing the two input fields (using DateJS or something else) to ensure the start_time is not greater than the end_time?
Any help would be great.
Upvotes: 0
Views: 273
Reputation: 2385
You can use Date.parseExact
with the format revision presented by @matthewtole, or you should be able to just use 'Date.parse' as well.
Date.parseExact
will provide better performance, but if you're just parsing two values, the performance improvement of Date.parseExact
is probably not going to make much difference.
You can also use the .isBefore()
function to check if one Date occurs before the other.
Example
var d1 = Date.parse("07:15 AM");
var d2 = Date.parse("08:30 AM");
d1.isBefore(d2); // true
Hope this helps
Upvotes: 0
Reputation: 229
Why not using toString?
var g = new Date("2012-01-11 03:15 PM");
console.log(g.toString('HH:mm'));
just add a ficticious date in order to obtain a valid date string format. Since I guess you just need the Time not the date
It works fine with me.
Upvotes: 0
Reputation: 76219
Not exactly answering the question, but DateJS looks a bit outdated. I would suggest you take a look at Moment.js, where you can do this:
moment("03:15 PM", "hh:mm A").isAfter(moment("03:05 PM", "hh:mm A"));
// false
Upvotes: 1
Reputation: 3247
You need to add the AM/PM field to the format you're using to parse with. Try using
HH:mm tt
Instead of
HH:mm
Upvotes: 4