0

I want to check to see if a date is before today. If it is then I want to display the date but not the time, if it is today then I want to display the time and not the date. The date I am checking is in the dd-mm-yyy hh:mm format and so they do not compare.

Please see what I have below so far:

var created = '25-05-2012 02:15';
var now = new Date();

if (created < now) { 
  created_format = [ format the date to be 25-05-2012 ]
} else {
  created_format = [ format the date to be 02:15 ]
}

I have tried using now.dateFormat() and now.format() after seeing these in other examples but I get "is not a function" error messages.

JJJ
  • 32,902
  • 20
  • 89
  • 102
LeeTee
  • 6,401
  • 16
  • 79
  • 139
  • 1
    jQuery doesn't provide date features so I've retagged the question. – JJJ May 28 '12 at 09:53
  • possible duplicate of [Formatting a date in javascript](http://stackoverflow.com/questions/1056728/formatting-a-date-in-javascript) – JJJ May 28 '12 at 09:54

2 Answers2

1

Start by getting the parts of your date string:

var created = '25-05-2012 02:15';
var bits = created.split(/[-\s:]/);
var now = new Date(); 

// Test if it's today    
if (bits[0] == now.getDate() &&
    bits[1] == (now.getMonth() + 1) &&
    bits[2] == now.getFullYear() ) {

  // date is today, show time

} else {
  // date isn't today, show date
}

Of course there are other ways, but I think the above is the easiest. e.g.

var otherDate = new Date(bits[2], bits[1] - 1, bits[0]);
now.setHours(0,0,0,0);
if (otherDate < now) {
  // otherDate is before today
} else {
  // otherDate is not before today
}

Similarly, once you've converted the string to a date you can use getFullYear, getMonth, getDate to compare with each other, but that's essentially the same as the first approach.

RobG
  • 142,382
  • 31
  • 172
  • 209
0

You can use getTime method and get timestamp. Then you can compare it with current date timestamp.

Slawek
  • 583
  • 3
  • 9
  • 1
    -1 since the `getTime` method doesn't return a timestamp, it returns a number that is the milliseconds since the epoch. Also, don't reference [w3schools](http://w3fools.com/), reference the appropriate standard and MDN or MSDN for examples as appropriate. – RobG May 28 '12 at 10:14