PaRsH
PaRsH

Reputation: 1320

Getting date using day of the week

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.

Upvotes: 6

Views: 17322

Answers (3)

Rejwanul Reja
Rejwanul Reja

Reputation: 1491

You can use this....

public static void Main()
{ 
    //current date  
    DateTime dt = DateTime.UtcNow.AddHours(6);

    //you can use it custom date  
    var cmYear = new DateTime(dt.Year, dt.Month, dt.Day);

    //here 2 is the day value of the week in a date
    var customDateWeek = cmYear.AddDays(-2); 
    Console.WriteLine(dt);
    Console.WriteLine(cmYear);
    Console.WriteLine("Date: " + customDateWeek);
    Console.WriteLine();  
    Console.ReadKey();
}

Upvotes: 0

onefootswill
onefootswill

Reputation: 4107

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).

Upvotes: 2

Steve
Steve

Reputation: 216351

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();

Upvotes: 13

Related Questions