Home > Flex, FlexDateUtils, code, library > Flex Date Utils – daysInMonth

Flex Date Utils – daysInMonth

/**
 * Gets the days in the month
 * 
 * @param date	The date to check
 * 
 * @return		The number of days in the month
 */
public static function daysInMonth( date:Date ):Number {
	// get the first day of the next month
	var _localDate:Date = new Date( date.fullYear, DateUtils.dateAdd( DateUtils.MONTH, 1, date ).month, 1 );
	// subtract 1 day to get the last day of the requested month
	return DateUtils.dateAdd( DateUtils.DAY_OF_MONTH, -1, _localDate ).date;
}

I have found method to be quite useful. It returns the number of days in a month based upon the date passed in.

First I create a date to represent the first of the following month, then I subtract 1 day from that month, and return the day that that date represents, which is now the last day of the month requested.

To use this method, first import the package:

import com.flexoop.utilities.dateutils.DateUtils;

and then:

private var _dim:Number = DateUtils.daysInMonth( new Date( 2008, 1 ) );

_dim will now contain 29, as there were 29 days in February, 2008.

All methods in this series are describing code in the FlexDateUtils package I put on Google code.

  1. April 27th, 2009 at 17:27 | #1

    Very nice, saved me many hours of head scratching. Thank you!

  2. Gareth
    April 27th, 2009 at 19:57 | #2

    Glad to help.

  3. Jake
    July 2nd, 2010 at 16:20 | #3

    Thanks, very clever solution.

  1. No trackbacks yet.