Working With Dates - Part 4: Dealing With Weekdays
Test and Monitor | Posted February 08, 2007

Besides recognizing the date, month and year, you often need to know on which day of the week a certain date falls. The Utilities.DayOfWeek method performs this task. It accepts the variant date and returns the number of the week day that corresponds to it. The returned number ranges between 1 and 7, where 1 corresponds to Sunday, 2 - to Monday, and so forth. The sample code below obtains the current date, calculates the day of the week and posts the name of the day to the log.

Note: The DayOfWeek method uses the United States system of week notation where the week is considered to start on Sunday and end on Saturday. However, the ISO 8601 “Data elements and interchange formats – Information interchange – Representation of dates and times” standard recommends another system of a week notation. In this system the week starts on Monday and ends on Sunday. To convert the US Week day number to ISO 8601 you can use the following routine. The result of this function is also an integer number, but 1 corresponds to Monday, 2 to Tuesday and so on.

In addition to the day of the week, we can find out the week boundaries that the specified date belongs, that is, calculate the dates that the week starts and ends. This could be done using the following two routines. Here the number of a week day is subtracted from the specified date to get the beginning of a week, and to get the end of the week, six days are added to the calculated date.

Note: Since the routines use the Utilities.DayOfWeek method, which returns the US week day number, the dates returned by the routines are Sunday and Saturday, correspondingly. To apply the ISO 8601 week day notation, you should use the last code line, where the the Utilities.DayOfWeek call is replaced with a call to ISODayOfWeek function. In this case the first routine would return the date that falls on Monday and the second one, the date that falls on Sunday.

Another frequent operation when dealing with dates is calculating the number of weeks that have passed since the beginning of the year. First we should clarify what week should be considered as the first week of a year. According to the ISO 8601 standard, the first week of a year is a week with the majority (four or more) of days in the starting year. In our case it is better to use another equivalent definition of the first week: the week with the date, January, 4th.

Here is the routine that calculates the week number in compliance with this rule. It accepts the date that belongs to the desired week, determines the end of this week and the end of the week that includes January 4, and that calculates the week number as the difference between those two values divided by 7.