Recipe 7.15. Determining the Day of the Week for a Date


Problem

You want to get a number or a string representing the day of the week for a given date.

Solution

Sample code folder: Chapter 07\ DayOfWeek

Use the Date's DayOfWeek property, which returns a number from 0 (Sunday) to 6 (Saturday) for the day of the week, or use its ToString() method to return the week-day name. You can also use various string-formatting options of the String.Format() method to return either the short or longer string name for the day of the week.

Discussion

If you want a number representation of the day of the week, the Date object's DayOfWeek property provides this directly. By default it returns 0 for Sunday, 1 to 5 for the workdays Monday through Friday, and 6 for Saturday.

To get the name of the weekday, call the DayOfWeek's ToString() method:

 MsgBox(Today.DayOfWeek.ToString()) 

To get an abbreviated version of the weekday name, apply the "ddd" formatting as you convert the date to a string. (Use "dddd" for the full weekday name.) The following lines of code demonstrate these techniques:

 Dim rightNow As Date = Now Dim weekDay As Integer = rightNow.DayOfWeek Dim weekDayShort As String = Format(rightNow, "ddd") Dim weekDayLong As String = String.Format("{0:dddd}", _    rightNow) Dim results As String = String.Format( _    "Today's day of the week: {0}, or {1}, or {2}", _    weekDay, weekDayShort, weekDayLong) MsgBox(results) 

Figure 7-15 shows the results as displayed by the message box in the last line of the example code.

Figure 7-15. Getting the day of the week either as a number from 0 to 6 or as a short or longer string name





Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net