A co-worker of mine is learning to program and decided to write a calendar program. He needed a way to find out what day of the week the first day of the month would be. In his explaining of how he was doing it we came up with the following code that would work for his needs.
17 static void Main(string[] args)
18 {
19
20 string date = "1-1-09";
21 string dofw = GetDayOfWeekFromString(date);
22
23 }
24
25 private static string GetDayOfWeekFromString(string date)
26 {
27 DateTime desiredDay = new DateTime();
28 DateTime.TryParse(date, out desiredDay);
29 return desiredDay.DayOfWeek.ToString();
30 }
After I gave him that code I decided to just pack it into an extension function. Like so.
36 public static string GetFirstDayOfMonthDayOfWeek(this DateTime dt)
37 {
38 DateTime firstOfMonth = new DateTime();
39 if (DateTime.TryParse(string.Format("{0}/1/{1}", dt.Month, dt.Year), out firstOfMonth))
40 {
41 return firstOfMonth.DayOfWeek.ToString();
42 }
43 return string.Empty;
44 }
Which can be called like this.
21 string dofw = DateTime.Now.GetFirstDayOfMonthDayOfWeek();
Hope someone else finds it of use.