如何获取星期几的整数值
如何以整数格式获取一周中的某一天?我知道 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
How do I get the day of a week in integer format? I know ToString will return only a string.
DateTime ClockInfoFromSystem = DateTime.Now;
int day1;
string day2;
day1= ClockInfoFromSystem.DayOfWeek.ToString(); /// it is not working
day2= ClockInfoFromSystem.DayOfWeek.ToString(); /// it gives me string
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
以字符串形式获取 Enum(例如 DayOfWeek)的整数值的正确方法是:
The correct way to get the integer value of an Enum such as DayOfWeek as a string is:
试试这个。它会工作得很好:
Try this. It will work just fine:
另一种获取星期一(整数值 1)和星期日(整数值 7)的方法
Another way to get Monday with integer value 1 and Sunday with integer value 7
正确答案,确实是获取int值的正确答案。
但是,如果您只是检查以确保今天是星期日...请考虑使用以下代码,而不是转换为 int。这提供了更多的可读性。
The correct answer, is indeed the correct answer to get the int value.
But, if you're just checking to make sure it's Sunday for example... Consider using the following code, instead of casting to an int. This provides much more readability.
可读性很重要。
如果您需要一个整数:
如果您需要一个工作日整数字符串:
不要使用推荐的 ToString 转换,因为大多数程序员必须查找它以确保它是一个整数字符串,而不是一个月中的某一天。真的是微软吗?
要更改为一周的开始,请添加从星期日起的天数 mod 7。从星期日开始倒数以获得天数,例如从星期日倒数 1 是星期六,从星期日倒数 2 是星期五,等等。
Readability counts.
If you need an integer:
If you need a string of the weekday integer:
Do not use the recommended ToString conversion, because the majority of programmers are going to have to look it up to make sure that it's a string of the integer and not day of month. Really Microsoft?
To change to start of week, add the number of days from Sunday mod 7. Count backwards from Sunday to get the number of days, e.g. 1 back from Sunday is Saturday, 2 back from Sunday is Friday, etc.
使用
Use
一周的第一天:星期日(值为零)
First day of the week: Sunday (with a value of zero)
如果要将一周的第一天设置为整数值 1 的星期一和整数值 7 的星期日
If you want to set first day of the week to Monday with integer value 1 and Sunday with integer value 7