Danny Nimmo
Danny Nimmo

Reputation: 684

Is it possible for a regex to know whether a date is a weekend or not?

Using javascript I need to validate a form field containing a date in the format: 21/04/2010. The date must be a weekday. Is it possible to create a regular expression for this or is there another, better way to do it?

Upvotes: 4

Views: 1728

Answers (5)

Matthew Flaschen
Matthew Flaschen

Reputation: 284836

Regex is clearly the wrong tool. Use Date.getDay():

var d = new Date();
var parts = dateStr.split("/");
// Date of month is 0-indexed.
var d = new Date(parts[2], parts[1] - 1, parts[0]);
var day = d.getDay();
if(day == 0 || day == 6)
{
  // weekend
}

Upvotes: 7

spender
spender

Reputation: 120480

The Javascript Date.parse function is only specified to used IETF standard time (e.g. "Aug 9, 1995"), so is not suited to your requirement. For 21/04/2010 you'll need to split it yourself and use the Date constructor to assemble a date. It would probably be safer to use something tried and tested. Have you looked at datejs?

Upvotes: 1

D.Shawley
D.Shawley

Reputation: 59563

The simple answer is NO. Use Date.getDay() since it is made for precisely that purpose.

Upvotes: 0

Anurag
Anurag

Reputation: 141879

Use getDay() which returns an integer from 0-6 where 0 is Sunday, and 6 is Saturday.

If the value is 1-5, then it's a weekday.

0 or 6 means it's a weekend.

Upvotes: 4

Benbob
Benbob

Reputation: 14254

Javascript has a date class. See http://www.w3schools.com/jsref/jsref_obj_date.asp

What you will need to do is create your Date object:

date = new Date(2010, 5, 19); //Year, month, day

Note the month is zero indexed, so subtract by 1. This is June

Then get the day:

day = date.getDay(); //Day is also 0 indexed.

var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

document.write("Today is " + weekday[date.getDay()]);

Upvotes: 3

Related Questions