Click here to Skip to main content
Click here to Skip to main content

Date on Day Of the Week

By , 2 Oct 2011
 
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:
 
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Steven.Pinto2000
United States United States
Member
Social Group (No members)

No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralReason for my vote of 5 good logic instead of going for forl... PinmemberSantoshyy10 Oct '11 - 18:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 2 Oct 2011
Article Copyright 2011 by Steven.Pinto2000
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid