简体   繁体   English

C6中VB6的WeekDay函数的等价性

[英]Equivalent of WeekDay Function of VB6 in C#

In VB6 code, I have the following: 在VB6代码中,我有以下内容:

dim I as Long 

I = Weekday(Now, vbFriday) 

I want the equivalent in C#. 我想要C#中的等价物。 Can any one help? 任何人都可以帮忙吗?

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天。

你的意思是DateTime.DayOfWeek属性?

DayOfWeek dow = DateTime.Now.DayOfWeek;

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将它重新调整到除星期日之外的另一天,但是......

I don't think there is an equivalent of the two argument form of VB's Weekday function. 我不认为VB的工作日函数有两种形式。

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天。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM