JustStarting
JustStarting

Reputation: 287

javascript / jquery compare datetime values

Seems to be a simple and commonly asked question but after googling for a while havent come up with an answer.

Very simply, I have two variables each with a datetime value in format yyyy-mm-dd hh:mm

I want to compare which is bigger and perform logic accordingly:

example: here

var fromDate = '2014-02-14 07:00';
var toDate = '2014-02-14 07:00';
if (Date.parse(fromDate) > Date.parse(toDate)) {
    alert("Invalid Date Range!\nStart Date cannot be after End Date!")
} else {
    alert("VALID Date Range!\n Start Date is before End");
}

The above continuously returns the successful validation.

Any advice, suggestions? examples? Thanks,

Upvotes: 0

Views: 3127

Answers (2)

JustStarting
JustStarting

Reputation: 287

this is real ugly but serves the purpose...

    var fromDate = '2014-02-27 09:00';
    fromDate=fromDate.replace("-", "/");
    fromDate=fromDate.replace("-", "/");
    var toDate = '2014-02-27 10:00';
    toDate=toDate.replace("-", "/");
    toDate=toDate.replace("-", "/");


var fromDate=(new Date(fromDate).getTime()/1000);
var toDate=(new Date(toDate).getTime()/1000);

if(fromDate>toDate){
    alert('CORRECT');
} else {
    alert('INCORRECT, from after to');
}

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074465

It happens that the format you're using can be compared lexigraphically. So no parsing required:

var fromDate = '2014-02-14 07:00';
var toDate = '2014-02-14 07:00';
if (fromDate > toDate) {
    alert("Invalid Date Range!\nStart Date cannot be after End Date!");
} else {
    alert("VALID Date Range!\n Start Date is before End");
}

This is because the most significant fields precede the less significant fields, throughout the string.

But if you really want date/time values, that string format isn't directly supported by the specification. You have three choices:

  1. Use a library like MomentJS.

  2. Massage the string so that it's in a supported format, but be aware that until ES5, there was no standard format dictated by the spec.

  3. Do it yourself

The latter looks something like this:

function parseMyDate(str) {
    var parts = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})/.exec(str);
    if (!parts) {
        return null;
    }
    return new Date(parseInt(parts[1], 10),      // Year
                    parseInt(parts[2], 10) - 1), // Month
                    parseInt(parts[3], 10),      // Day
                    parseInt(parts[4], 10),      // Hours
                    parseInt(parts[5], 10));      // Minutes
}

Then use parseMyDate where you have Date.parse above.

Upvotes: 3

Related Questions