Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Date on Day Of the Week

0.00/5 (No votes)
2 Oct 2011 1  
Day of the week
I had come across a requirement wherein I had to send some reports to the user on the first day of the month and on the last day of the month based on the day selected by the Admin (e.g., the Day of the week provided by Admin is Sunday).

Well, here is the logic which does the trick:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
namespace ConsoleApplication3
{
    class Demo
    {
        static void Main(string[] args)
        {

            //This was a Interview Question
            //where in i want to find the first 
            DateTime FindLastDate = new DateTime(DateTime.Now.Year ,DateTime.Now.Month , 1).AddMonths(1).AddDays(-1);
            int i=(int)DayOfWeek.Saturday  ;
            int z = (int)FindLastDate.DayOfWeek ;
            DateTime LastDay = FindLastDate.AddDays(z >= i ? (-z + i) : -(z + 7 - i));
            Console.WriteLine("The Date Of The Last " + DayOfWeek.Saturday.ToString() + " Of the Month Is" + LastDay.ToShortDateString());
            DateTime FindFirstDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            z = (int)FindFirstDay.DayOfWeek;
            DateTime FirstDay = FindFirstDay.AddDays(z > i ? (7 - z) + i : (7 - z)-(7-i));
            Console.WriteLine("The Date Of The First " + DayOfWeek.Saturday.ToString() + " Of the Month Is" + FirstDay.ToShortDateString());
            Console.ReadLine();
        }        
    }
}


Please post your comments and let me know how you like this trick.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here