C# 如何获取星期几的整数值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9199080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:20:27  来源:igfitidea点击:

How to get the integer value of day of week

c#datetimedayofweekdate-conversion

提问by akshaykumar6

How do I get the day of a week in integer format? I know ToString will return only a string.

如何以整数格式获取星期几?我知道 ToString 只会返回一个字符串。

DateTime ClockInfoFromSystem = DateTime.Now;
int day1;
string day2;
day1= ClockInfoFromSystem.DayOfWeek.ToString(); /// it is not working
day2= ClockInfoFromSystem.DayOfWeek.ToString(); /// it gives me string

采纳答案by Joe

Use

day1 = (int)ClockInfoFromSystem.DayOfWeek;

回答by FiveTools

day1= (int)ClockInfoFromSystem.DayOfWeek;

回答by FiveTools

int day = (int)DateTime.Now.DayOfWeek;

First day of the week: Sunday (with a value of zero)

一周的第一天:星期日(值为零)

回答by Martin Sansone - MiOEE

If you want to set first day of the week to Monday with integer value 1 and Sunday with integer value 7

如果要将一周的第一天设置为整数值为 1 的星期一和整数值为 7 的星期日

int day = ((int)DateTime.Now.DayOfWeek == 0) ? 7 : (int)DateTime.Now.DayOfWeek;

回答by Michael Murphy

DateTime currentDateTime = DateTime.Now;
int week = (int) currentDateTime.DayOfWeek;

回答by RaviKant Hudda

Try this. It will work just fine:

尝试这个。它会工作得很好:

int week = Convert.ToInt32(currentDateTime.DayOfWeek);

回答by Rob Sedgwick

The correct way to get the integer value of an Enum such as DayOfWeek as a string is:

将 Enum 的整数值(例如 DayOfWeek)作为字符串获取的正确方法是:

DayOfWeek.ToString("d")

回答by Ruslan Hayduk

Another way to get Monday with integer value 1 and Sunday with integer value 7

获得整数值为 1 的星期一和整数值为 7 的星期日的另一种方法

int day = ((int)DateTime.Now.DayOfWeek + 6) % 7 + 1;