使用星期几获取日期 [英] Getting date using day of the week

查看:81
本文介绍了使用星期几获取日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用星期几查找日期时遇到问题。

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

2013年1月8日是星期二。

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.

推荐答案

您可以使用枚举 DayOfWeek


DayOfWeek枚举代表每周$ 7的日历
中的星期几。在
枚举中,常量的值从DayOfWeek.Sunday到DayOfWeek.Saturday。如果
转换为整数,则其值的范围从零(表示
DayOfWeek.Sunday)到六(表示DayOfWeek.Saturday)。

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

现在您可以使用

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

这篇关于使用星期几获取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆