等效于 C# 中 VB6 的 WeekDay 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/400421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Equivalent of WeekDay Function of VB6 in C#
提问by RBS
In VB6 code, I have the following:
在VB6代码中,我有以下内容:
dim I as Long
I = Weekday(Now, vbFriday)
I want the equivalent in C#. Can any one help?
我想要 C# 中的等价物。任何人都可以帮忙吗?
采纳答案by LeppyR64
public static int Weekday(DateTime dt, DayOfWeek startOfWeek)
{
return (dt.DayOfWeek - startOfWeek + 7) % 7;
}
This can be called using:
这可以使用以下方法调用:
DateTime dt = DateTime.Now;
Console.WriteLine(Weekday(dt, DayOfWeek.Friday));
The above outputs:
以上输出:
4
as Tuesday is 4 days after Friday.
因为周二是周五之后的 4 天。
回答by Lasse V. Karlsen
You mean the DateTime.DayOfWeekproperty?
你的意思是DateTime.DayOfWeek属性?
DayOfWeek dow = DateTime.Now.DayOfWeek;
回答by Charles Bretana
Yes, Each DateTime value has a built in property called DayOfWeek that returns a enumeration of the same name...
是的,每个 DateTime 值都有一个名为 DayOfWeek 的内置属性,它返回一个相同名称的枚举......
DayOfWeek dow = DateTime.Now.DayOfWeek;
If you want the integral value just cast the enumeration value to an int.
如果您想要整数值,只需将枚举值转换为 int。
int dow = (int)(DateTime.Now.DayOfWeek);
You'll have to add a constant from 1 to 6 and do Mod 7 to realign it to another day besides Sunday, however...
您必须添加一个从 1 到 6 的常量并执行 Mod 7 以将其重新调整到周日以外的另一天,但是...
回答by Powerlord
I don't think there is an equivalent of the two argument form of VB's Weekday function.
我认为没有与 VB 的 Weekday 函数的两个参数形式等效的形式。
You could emulate it using something like this;
你可以使用这样的东西来模拟它;
private static int Weekday(DateTime date, DayOfWeek startDay)
{
int diff;
DayOfWeek dow = date.DayOfWeek;
diff = dow - startDay;
if (diff < 0)
{
diff += 7;
}
return diff;
}
Then calling it like so:
然后像这样调用它:
int i = Weekday(DateTime.Now, DayOfWeek.Friday);
It returns 4 for today, as Tuesday is 4 days after Friday.
今天返回 4,因为星期二是星期五之后的 4 天。