Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of WeekDay Function of VB6 in C#

In VB6 code, I have the following:

dim I as Long 

I = Weekday(Now, vbFriday) 

I want the equivalent in C#. Can any one help?

like image 752
RBS Avatar asked Dec 30 '08 14:12

RBS


4 Answers

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.

like image 140
LeppyR64 Avatar answered Sep 21 '22 14:09

LeppyR64


You mean the DateTime.DayOfWeek property?

DayOfWeek dow = DateTime.Now.DayOfWeek;
like image 41
Lasse V. Karlsen Avatar answered Sep 22 '22 14:09

Lasse V. Karlsen


Yes, Each DateTime value has a built in property called DayOfWeek that returns a enumeration of the same name...

DayOfWeek dow = DateTime.Now.DayOfWeek;

If you want the integral value just cast the enumeration value to an 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...

like image 39
Charles Bretana Avatar answered Sep 19 '22 14:09

Charles Bretana


I don't think there is an equivalent of the two argument form of VB's Weekday function.

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.

like image 34
Powerlord Avatar answered Sep 18 '22 14:09

Powerlord