views:

1562

answers:

4

I have to convert some of my VB6 Code to C# , In my VB6 I am having code like

dim I as Long 

I = Weekday(Now, vbFriday) 


I want equivalent of the same in C#

Can any one Help ?

+1  A: 

You mean the DateTime.DayOfWeek property?

DayOfWeek dow = DateTime.Now.DayOfWeek;
Lasse V. Karlsen
+1  A: 

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...

Charles Bretana
+1  A: 

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.

R. Bemrose
+2  A: 
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.

Jason Lepack