Search code examples
c#visual-studio-2008vb6.net-3.5dayofweek

Get day of week from current date and specifying first day of week


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.


Solution

  • 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;