Getting date using day of the week

13,610

Solution 1

You can use the enumeration DayOfWeek

The DayOfWeek enumeration represents the day of the week in calendars that have seven days per week. The value of the constants in this enumeration ranges from DayOfWeek.Sunday to DayOfWeek.Saturday. If cast to an integer, its value ranges from zero (which indicates DayOfWeek.Sunday) to six (which indicates DayOfWeek.Saturday).

We can use the conversion to integer to calculate the difference from the current date of the same week day

DateTime dtOld = new DateTime(2013,1,8);
int num = (int)dtOld.DayOfWeek;
int num2 = (int)DateTime.Today.DayOfWeek;
DateTime result = DateTime.Today.AddDays(num - num2);

This also seems appropriate to create an extension method

public static class DateTimeExtensions
{
    public static DateTime EquivalentWeekDay(this DateTime dtOld)
    {
        int num = (int)dtOld.DayOfWeek;
        int num2 = (int)DateTime.Today.DayOfWeek;
        return DateTime.Today.AddDays(num - num2);
    }
}   

and now you could call it with

DateTime weekDay = Convert.ToDateTime("01/08/2013").EquivalentWeekDay();

Solution 2

I may be a bit late to the party, but my solution is very similar:

DateTime.Today.AddDays(-(int)(DateTime.Today.DayOfWeek - DayOfWeek.Tuesday));

This will get the Tuesday of the current week, where finding Tuesday is the primary goal (I may have misunderstood the question).

Share:
13,610
PaRsH
Author by

PaRsH

.NET Programmer

Updated on June 09, 2022

Comments

  • PaRsH
    PaRsH almost 2 years

    I have problem in finding the date using day of the week.

    For example : i have past date lets say,

    Date date= Convert.TodateTime("01/08/2013");
    

    08th Jan 2013 th Day of the week is Tuesday.

    Now i want current week's tuesday's date. How i can do it.

    Note : The past date is dynamic. It will change in every loop.