Getting date using day of the week

自闭症网瘾萝莉.ら 提交于 2019-12-10 17:28: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.


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



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




回答3:


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


来源:https://stackoverflow.com/questions/15875443/getting-date-using-day-of-the-week

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!