Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 771
PaRsH Avatar asked Apr 08 '13 09:04

PaRsH


People also ask

How do you format the date with the day of the week?

Format cells to show dates as the day of the week Under Category, click Custom, and in the Type box, type dddd for the full name of the day of the week (Monday, Tuesday, and so on), or ddd for the abbreviated name of the day of the week (Mon, Tue, Wed, and so on).

Which is the day of the week?

According to international standard ISO 8601, Monday is the first day of the week. It is followed by Tuesday, Wednesday, Thursday, Friday, and Saturday. Sunday is the 7th and last day of the week.

How do I get the day of the week in Python?

Use the weekday() method The weekday() method returns the day of the week as an integer, where Monday is 0 and Sunday is 6. For example, the date(2022, 05, 02) is a Monday. So its weekday number is 0.


1 Answers

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();
like image 87
Steve Avatar answered Oct 14 '22 11:10

Steve