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