Getting date using day of the week

2019-06-24 07:30发布

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.

3条回答
爷、活的狠高调
2楼-- · 2019-06-24 07:55

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();
查看更多
smile是对你的礼貌
3楼-- · 2019-06-24 08:05

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();
}
查看更多
手持菜刀,她持情操
4楼-- · 2019-06-24 08:10

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

查看更多
登录 后发表回答