2

I have 2 dates and I one to check if one date comes before another one. I know you have to parse the date to a JS date object and then check it with milliseconds.

But the problem is, in my database dateTimes are stored like this.

10-mei-2012 09:36

So my question is how can I compare two of these dates and check that date 1 comes before date2? Oh and for the record, I am also using jquery to get these values.

var dateB = $('#DATUM_BEGIN').val();
var dateE = $('#DATUM_EINDE').val();

kind regards

Stef

Steaphann
  • 2,797
  • 6
  • 50
  • 109
  • I just saw that this question was already asked. http://stackoverflow.com/questions/5000693/comparing-dates-in-jquery – CyrillC May 10 '12 at 08:03

4 Answers4

5

In that format you can compare strings as-is, it is safe. So use just

if (dateB < dateE) ...
zerkms
  • 249,484
  • 69
  • 436
  • 539
0

http://www.datejs.com/ could be helpful. it is a jquery Plugin to compare Dates.

CyrillC
  • 557
  • 1
  • 3
  • 15
0

The format you show is "mostly" ISO-8601 combined-date format which is by design comparable as plain text.

The only difference between what you have and pure ISO-8601 is that there would need to be a 'T' where the space character is.

http://en.wikipedia.org/wiki/ISO_8601

So, if you can sort the strings you know which one comes first.

caskey
  • 12,305
  • 2
  • 26
  • 27
-2

Here's a function found while googling that converts MySQL DATETIME to a JS Object

function mysqlTimeStampToDate(timestamp) {
  var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
  var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
  return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
}

Here's one example of how to use it:

$(function(){
  var dateB = mysqlTimeStampToDate($('#DATUM_BEGIN').val());
  var dateE = mysqlTimeStampToDate($('#DATUM_EINDE').val());

  if(dateB < dateE){
    // dateB is older
  } else {
    // dateB is newer
  }
});
Pastor Bones
  • 7,183
  • 3
  • 36
  • 56