Flex Date Utils – dayOfWeekAsNumber
// Days of week public static const MONDAY:String = "monday"; public static const TUESDAY:String = "tuesday"; public static const WEDNESDAY:String = "wednesday"; public static const THURSDAY:String = "thursday"; public static const FRIDAY:String = "friday"; public static const SATURDAY:String = "saturday"; public static const SUNDAY:String = "sunday"; // a generic object for holding day of the week values private static var _objDaysOfWeek:Object = null; public static function get objDaysOfWeek():Object { if ( !_objDaysOfWeek ) { _objDaysOfWeek = {}; _objDaysOfWeek[ DateUtils.SUNDAY ] = 0; _objDaysOfWeek[ DateUtils.MONDAY ] = 1; _objDaysOfWeek[ DateUtils.TUESDAY ] = 2; _objDaysOfWeek[ DateUtils.WEDNESDAY ] = 3; _objDaysOfWeek[ DateUtils.THURSDAY ] = 4; _objDaysOfWeek[ DateUtils.FRIDAY ] = 5; _objDaysOfWeek[ DateUtils.SATURDAY ] = 6; } return _objDaysOfWeek; } /** * Formats a date to the numeric version of the day of the week * * @param strDayOfWeek The day of week to convert * * @return A formatted day of week or -1 if day not found */ public static function dayOfWeekAsNumber( strDayOfWeek:String ):Number { return ( objDaysOfWeek[ strDayOfWeek ] >= 0 ) ? objDaysOfWeek[ strDayOfWeek ] : -1; }
This method will actually take a string that represents the day of the week, and will convert that to the numeric representation in Flex for that day of the week, ranging from 0-6.
I actually created a generic object that would hold all of the values for the days of the week to make my life easier when trying to return and reference values in it. I also created constants for all of the days of the week, so anyone calling any method that needs a string of the day of the week, can simply reference the constants, instead of trying to guess what I called the days of the week.
The method tries to reference whatever string is passed to it in the generic dayOfWeek object, and will return the value it finds, or if the object does not contain that string, it will return -1. As long as you use the constants, the -1 should never be returned.
So in order to use this method, first import the package
import com.flexoop.utilities.dateutils.DateUtils;
and then:
private var _dow:Number = DateUtils.dayOfWeekAsNumber( DateUtils.MONDAY );
_dow would now be 1, as _objDaysOfWeek[ DateUtils.MONDAY ] is equal to 1. I tend to use this method whenever I’m passing a day of the week value to one of my other methods, just so I don’t confuse the actual day value ( i.e. using 1-7 instead of 0-6 ).
All methods in this series are describing code in the FlexDateUtils package I put on Google code.