表示星期几的 DateTime 对象
如何将 1 到 7 之间的数字转换为 C# 中代表星期几的 DateTime 对象? 这些数字来自我正在解析的 XML 文件。 我正在检索包含 1 到 7 之间的数字的字段的每个实例,该数字代表星期日到星期六之间的一周中的一天。
How can I convert a number between 1 and 7 into a DateTime object in C# which represents the day of the week? The numbers are coming from a XML file which I am parsing. I am retrieving each instance of a field containing a number between 1 and 7 which represents a day of the week between Sunday and Saturday.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我假设转换为 DayOfWeek 对象将为您提供一周中的一天
就 DateTime 对象而言,该对象代表特定的一天,不一定是一周中的随机一天。 如果您想要实现这一目标,您可以尝试在特定日期中添加天数。
http://msdn.microsoft.com/ en-us/library/system.dayofweek.aspx
I would assume casting to a DayOfWeek object would give you a day of the week
As far as a DateTime object goes, the object represents a specific day, not necessarily a random day of the week. You may try adding a # of days to a specific date if this is what you're trying to achieve.
http://msdn.microsoft.com/en-us/library/system.dayofweek.aspx
为了获取
DateTime
,您需要希望工作日属于特定的日期范围(因为DateTime
是特定的日期和时间,并且工作日则不然)。有一个
DayOfWeek
枚举(其值实际上范围为 0-6)。 如果您需要的只是代表星期几,那么您应该能够将 int 转换为DayOfWeek
,例如......如果您需要实际的
DateTime
,你需要一个开始日期。 然后您可以执行以下操作...这将为您提供您所描述的一周中的下一个发生实例的日期时间。
In order to get a
DateTime
, you'd need a specific range of dates that you want the weekday to fall under (since aDateTime
is a specific date and time, and a weekday isn't).There is a
DayOfWeek
enumeration (whose values actually range from 0-6). If all you need is something to represent the day of the week, then you should be able to cast your int to aDayOfWeek
like..If you need an actual
DateTime
, you'll need a start date. You could then do...This will give you a DateTime for the next occuring instance of the day of the week you're describing.
DayOfWeek.Sunday 为零,因此您可以从已知为星期日的任意固定日期开始,并添加 0 到 6 之间的值:
但我不确定您为什么需要这个。
如果您只想获取星期几的本地化版本,如下所示:
另一种方法是使用 DateTimeFormatInfo.DayNames 或 DateTimeFormatInfo.AbbreviatedDayNames 作为您想要的区域性。
DayOfWeek.Sunday is zero, so you could start with an arbitrary fixed date that you know to be Sunday, and add a value between 0 and 6:
I'm not sure why you would want this though.
If you only want it to get a localized version of the day of the week as in:
an alternative would be to use DateTimeFormatInfo.DayNames or DateTimeFormatInfo.AbbreviatedDayNames for the culture you want.
DateTime
实例始终表示完整的日期,而不能仅表示一周中的某一天。 如果实际日期并不重要,则取任意星期一(假设 0 代表星期一)并添加当天的数字。否则我同意 Adam Robinson 的回答 - 如果您只想保留一周中的某一天,请坚持使用 DayOfWeek 枚举(零是星期日)而不是使用整数。
A
DateTime
instance represents alway a complete date and cannot only represent a day of the week. If the actual date does not matter, take any monday (assuming 0 represents monday) and just add the number of the day.Else I agree with Adam Robinson's answer - if you just want to hold the day of a week, stick with the DayOfWeek enum (zero is sunday) instead of using an integer.