在C#7.3版本中获取今天是星期几,并转化为数字1-7的C#代码
时间: 2024-12-15 21:30:25 浏览: 5
在C# 7.3版本中,你可以使用DateTime类的DayOfWeek属性以及Enum.Parse方法来获取今天是星期几并将其转换为数字(1代表Monday,2代表Tuesday,依此类推)。以下是一个示例代码:
```csharp
using System;
class Program
{
public enum WeekDays
{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7
}
static void Main(string[] args)
{
DateTime today = DateTime.Today;
WeekDays dayOfWeekNumber = (WeekDays)Enum.Parse(typeof(WeekDays), today.DayOfWeek.ToString());
Console.WriteLine($"Today is {dayOfWeekNumber}");
// 如果需要输出数字,可以直接打印 dayOfWeekNumber 的值
相关问题
获取今天是星期几,并转化为数字1-7的C#代码
在C#中,你可以使用DateTime对象的DayOfWeek属性来获取当前日期是一周中的哪一天,然后通过枚举转换为对应的数字。以下是相应的代码示例:
```csharp
using System;
public class Program
{
public static void Main()
{
DateTime today = DateTime.Today;
DayOfWeek dayOfWeek = today.DayOfWeek; // 获取今天是星期几
// 枚举值对应关系:Monday = 1, Tuesday = 2, ..., Sunday = 7
int numericDay = (int)dayOfWeek switch
{
DayOfWeek.Monday => 1,
DayOfWeek.Tuesday => 2,
DayOfWeek.Wednesday => 3,
DayOfWeek.Thursday => 4,
DayOfWeek.Friday => 5,
DayOfWeek.Saturday => 6,
DayOfWeek.Sunday => 7,
_ => throw new ArgumentOutOfRangeException("Invalid day of week")
};
Console.WriteLine($"Today is {numericDay}th.");
获取今天是星期几的C#代码
在C#中,你可以直接使用`DateTime`类的`DayOfWeek`属性获取当前日期是一周中的哪一天。以下是一个简单例子:
```csharp
using System;
class Program
{
static void Main()
{
// 获取当前日期
DateTime currentDate = DateTime.Today;
// 获取当前日期对应的星期几
DayOfWeek dayOfWeek = currentDate.DayOfWeek;
Console.WriteLine($"今天是{dayOfWeek.ToString("dddd")}, 星期{dayOfWeek}");
// 输出:今天是星期二, 星期2 (假设今天是周二)
}
}
```
在这个代码中,`DayOfWeek`枚举包含一周中的每一天,如`DayOfWeek.Monday`到`DayOfWeek.Sunday`。`ToString("dddd")`用于将枚举值转换为完整的英文星期名称,例如"Monday"。
阅读全文