2

I need to get the current weekday number of the current week.

If I use DateTime.Now.DayOfWeek I get Monday, but it would be much easier to work with if I get 1 for Monday, 7 for Sunday etc. Thanks beforehand!

trashr0x
  • 6,457
  • 2
  • 29
  • 39
MaxK123
  • 390
  • 3
  • 15
  • Does this answer your question? [Get int value from enum in C#](https://stackoverflow.com/questions/943398/get-int-value-from-enum-in-c-sharp) – Magnetron Jun 14 '21 at 14:10

3 Answers3

4

You can use this:

day1 = (int)DateTime.Now.DayOfWeek;
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
faheem999
  • 52
  • 3
2

You can create an extension method to hide the implementation details.

Using an extension method and constraining T to IConvertible does the trick, but as of C# 7.3 Enum is an available constraint type:

public static class EnumExtensions
{
    public static int ToInt<T>(this T source) where T : Enum
    {
        return (int) (IConvertible) source;
    }
}

This then allows you to write:

DateTime.Now.DayOfWeek.ToInt();

Example:

Console.WriteLine(DayOfWeek.Monday.ToInt()); // outputs 1

Note: this solution assumes that int is used as the underlying Enum type.

trashr0x
  • 6,457
  • 2
  • 29
  • 39
2

DateTime.Now.DayOfWeek is an enum, and it is of (int) type, so the easiest way would be @faheem999 's answer. But, if you are dealing with Enums with unknown type's, such as (byte , sbyte , short , ushort , int , uint , long or ulong), then either you need to know Enum type, or use another method:

DayOfWeek dayOfWeek = DateTime.Now.DayOfWeek;
object val = Convert.ChangeType(dayOfWeek, dayOfWeek.GetTypeCode());

For more information, look at this question Get int value from enum in C#

Isi
  • 123
  • 1
  • 2
  • 13
  • Does this method work for evey type or are there exceptions? Will the object "val" be the number of the dayofweek? In my project I compare the daynumber in the week to a database Id (int). Can I compare an object with an int? – MaxK123 Jun 14 '21 at 21:14
  • 1
    This method, Returns an object of the specified type and whose value is equivalent to the specified object. In this case, because `dayOfWeek.GetTypeCode()` returns **int (because DateTime.Now.DayOfWeek is an enum, and it is of (int) type)** `object val` will become int. If you put another type there, it will convert to the specified type. However, it cannot convert another type to an enumeration value, even if the source type is the underlying type of the enumeration.For more information, [Convert.ChangeType](https://docs.microsoft.com/en-us/dotnet/api/system.convert.changetype?view=net-5.0) – Isi Jun 16 '21 at 05:37