Flex Date Utils – totalDayOfWeekInMonth, monthAsNumber
These 2 methods are quite useful. I use monthAsNumber quite frequently throughout the DateUtils library as it prevents any confusion about which month I am referencing (using the constants for a month rather than the numeric version, which in Flex and many programming languages is 0-11 rather than 1-12)
/** * Gets the total number of dayOfWeek in the month * * @param strDayOfWeek The day of week to check * @param date The date containing the month and year * * @return The number of <code>strDayOfWeek</code> in that month and year */ public static function totalDayOfWeekInMonth( strDayOfWeek:String, date:Date ):Number { var _startDate:Date = DateUtils.dayOfWeekIterationOfMonth( 1, strDayOfWeek, date ); var _totalDays:Number = DateUtils.dateDiff( DateUtils.DAY_OF_MONTH, _startDate, new Date( date.fullYear, date.month, DateUtils.daysInMonth( date ) ) ); // have to add 1 because have to include first day that is found i.e. if wed is on 2nd of 31 day month, would total 5, of if wed on 6th, would total 4 return Math.floor( _totalDays / 7 ) + 1; }
This method calculates the total number of a specific day of the week for a specified month. The method accepts dayOfWeek as a string (use one the constants to make this easier) and a date containing the month and year requested. It then returns a number with the total number of that day of the week for that month.
So in order to use this method, first import the package
import com.flexoop.utilities.dateutils.DateUtils;
and then:
private var _total:Number = DateUtils.totalDayOfWeekInMonth( DateUtils.Wednesday, new Date( 2009, DateUtils.monthAsNumber( JANUARY ) ) );
which would return 4, as there are 4 Wednesdays in January 2009
/** * Formats a month to the numeric version of the month * * @param strMonth The month to convert * * @return A formatted month or -1 if month not found */ public static function monthAsNumber( strMonth:String ):Number { return ( objMonth[ strMonth ] >= 0 ) ? objMonth[ strMonth ] : -1; }
This method takes a string version of the month, and then converts it to the numeric version of that month. I use objMonth[ strMonth ] >= 0 rather than just objMonth[ strMonth ], as 0 is also “false” and was returning -1 instead of 0 (for January). This is quite a useful method for me, and, even though it is more typing, I feel it makes more sense to someone skimming/reading the code, which prevents headaches in the future. I even found one example I gave that was using 1, when I actually meant 0, for January, so I altered the example to use this method to remove all confusion.
All methods in this series are describing code in the FlexDateUtils package I put on Google code.