Tag: ValidationResultEvent

Dates, how many days? (DateValidator)

Dates, how many days? (DateValidator)

It’s been a while since I last looked at this, and it annoys me that there isn’t a simple function to do this. So if you are wishing to find out how many days are in a month for a given year then feel free to use the below.

Of course it’s going to be virtually the same result for most years, but I still think it should be a function inside the Date class (or maybe a DateUtil class).

Start off with a standard Switch statement as all months (apart from February) have a fixed number of days.  This of course isn’t exactly rocket science but how do we figure out how many days February has?

Well the solution still isn’t rocket science but I like it, if you create a DateValidator and you give it a date of 29/02/2003 (yes this is a UK date – date at the start) and get it to validate that, then it will fail as 2003 isn’t a leap year. So February for 2003 must only have 28 days.

That’s it.  You could of course just divide the year by 4 and check to see if there is a modulus of 0, if so then it is a leap year.  If you chose to use this approach you’d need to make sure that the date range you are using doesn’t include anything unusual (I’m not sure how constant the leap year really is, if it’s anything like the clocks going forward or back 1 or 2 hours then you’re best just using the internal date validation). The flash player gets its time from the operation system, so (AFAIK) its rules for working out if a date is valid is also comes from the operating system.

the below code also shows an example of using the DateValidator that doesn’t use the month/date/year input, which is another reason why I like it.

public function getNumberOfDaysInMonth(month : Number, year : Number) : Number{

  switch(month){

    case 0://January
    case 2://March
    case 4://May
    case 6://July
    case 7://August
    case 9://October
    case 11://December
    return 31;
    break;

    case 3://April
    case 5://June
    case 8://September
    case 10://November 
    return 30;
    break;

    case 1://February
    return getNumberOfDaysInFebruary(year);//
    break;

    default:
    return 0;//should never reach this - if it does then 0 is an error
  }
}

private function getNumberOfDaysInFebruary(year  : Number ) : Number {

  var isValid : DateValidator = new DateValidator();
  isValid.inputFormat = "DD/MM/YYYY";
  isValid.allowedFormatChars = "/";
  var result : ValidationResultEvent = isValid.validate("29/02/"+ year);
  if(result.results == null ){//29th is a valid date
    return 29;
  } else {//29th is NOT a valid date
    return 28;
  }
}

[ad name=”ad-1″]