7

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?

Daniel
  • 10,864
  • 22
  • 84
  • 115
RBS
  • 3,801
  • 11
  • 35
  • 33

4 Answers4

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

LeppyR64
  • 5,251
  • 2
  • 30
  • 35
  • 6
    The return value of the VB6 (and VB.NET) function is 1 based. `return ((dt.DayOfWeek - startOfWeek + 7) % 7) + 1;` – 300hp Sep 19 '12 at 18:56
4

You mean the DateTime.DayOfWeek property?

DayOfWeek dow = DateTime.Now.DayOfWeek;
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
3

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
  • 143,358
  • 22
  • 150
  • 216
2

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.

Powerlord
  • 87,612
  • 17
  • 125
  • 175