2

I am migrating a legacy VB6 project into C#.

I want to obtain the equivalent in C# from expression below:

Weekday(Date, vbMonday)

I know there is a function in C#:

int dayOfWeek = (int)DateTime.Today.DayOfWeek;

but how to specify that the first day of the week is Monday and then function DayOfWeek take it into account and return the correct value?

I need to obtain an int value.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Willy
  • 9,848
  • 22
  • 141
  • 284
  • 1
    It's really unclear what you're aiming to achieve. The `DayOfWeek` property returns a `DayOfWeek` enum value - that's unaffected by which is the first day of the week. What values are you expecting to get? – Jon Skeet Jun 06 '17 at 12:20

2 Answers2

4

You can get the first day of the week by calling CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek, but I think you can do without that.

The Weekday function returns 1 for Monday, just like DayOfWeek. The only special case is Sunday, which .NET returns as 0, while VB returns 7.

Just do the math:

int dayOfWeek = DateTime.Today.DayOfWeek == DayOfWeek.Sunday
                 ? 7
                 : (int)DateTime.Today.DayOfWeek;
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • Are you sure? From msdn documentation: https://msdn.microsoft.com/en-us/library/82yfs2zh(v=vs.90).aspx sunday in vb6 is 1, monday 2 and saturday 7 if you don't specify first day of week as parameter in WeekDay function, by default first day of week is sunday. In my example, you specify first day of week to be Monday by specifying it by argument in WeekDay function, so Monday is 1, Tuesday is 2, and Sunday is 7, this is how I understand. – Willy Jun 06 '17 at 12:43
  • Yes, but you set it to be `Monday = 1`, that is why it is 1 (so you deviate from the documentation). – Patrick Hofman Jun 06 '17 at 12:45
  • ok, so as in .NET you do not specify first day of the week, it is set by default to sunday, so sunday is 0 and monday is 1, tuesday 2,..., saturday 6. – Willy Jun 06 '17 at 12:46
  • The enum is. I don't use the actual first day of the week from the culture since you don't need that to do the math. – Patrick Hofman Jun 06 '17 at 12:47
  • And in vb6, using WeekDay(Date,vbMonday), if Monday is specified as first day of the week why Monday gets 1 and not 0? – Willy Jun 06 '17 at 12:49
  • Because VB dislikes 0. In this case it also has a different meaning (read the docs). – Patrick Hofman Jun 06 '17 at 12:49
0
DateTime dateValue = new DateTime(2008, 6, 11);



Console.WriteLine((int) dateValue.DayOfWeek);

// The example displays the following output: // 3

Console.WriteLine(dateValue.ToString("dddd"));

// The example displays the following output: // Wed

Console.WriteLine(dateValue.ToString("dddd"));

// The example displays the following output: // Wednesday

Rohit Poudel
  • 1,793
  • 2
  • 20
  • 24