matt
matt

Reputation: 44293

Javascript: check formatted date value against current date?

a text-input contains a german formatted date 15.09.2012 I simply use $('#wr_event_date').val() to query the value in the input-field.

I wonder how I can match that date agains "today"?

var eventDate = $('#wr_event_date').val();

   // if eventDate is older than today as in "is over" doSomething();

So basically I want to check if the eventDate is older than today and if so I want to doSomething();

Ideas on that? Thank you in advance.

Upvotes: 1

Views: 438

Answers (3)

João Silva
João Silva

Reputation: 91299

Unfortunately, you have to parse the date yourself. Then, fetch the current date with new Date(), reset the time part, and compare both dates:

var s = $('#wr_event_date').val().split(".");
var eventDate = new Date(s[2], s[1] - 1, s[0]);

var today = new Date();
today.setHours(0, 0, 0, 0); // reset time

if (eventDate.getTime() - today.getTime() < 0) { // event date is older than today
  doSomething();
}

DEMO.

Upvotes: 1

Danil Speransky
Danil Speransky

Reputation: 30453

var parts = '15.09.2012'.split('.')
var date = Date.parse(parts[1], parts[0] - 1, parts[2]);

if (date - new Date().getTime() > 24 * 60 * 60 * 1000) ...
​

Upvotes: 0

Vikdor
Vikdor

Reputation: 24124

If you could use a third party library, then moment.js provides the functions to parse date strings and manipulate dates.

Upvotes: 0

Related Questions