确定 NSDate 对象的日期组成部分(时区问题)
我如何确定某个 NSDate 对象是否属于某一天?例如,由于所有日期均以 GMT 时区计算,因此日期实际上可能是 8 号而不是 9 号。在计算天、月、星期几等时,考虑时区差异的最佳方法是什么?
How would I be able to determine if a certain NSDate object falls within a certain day? Since all dates calculate to the GMT time zone, a date maybe actually be on the 8th instead of the 9th, for example. What's the best way to account for the time zone difference when calculating things like days, months, day of week, etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSDate
是一个绝对时间点。当您想知道今天是哪一天时,您必须考虑您的特定时区。由于您通过NSCalendar
获取了NSDateComponents
,因此您可以在日历上使用setTimeZone:
来获取组件(月、日、小时等)。 )您感兴趣的时区。如果您处理“日历日期”(即应始终代表特定日期/月份而不是绝对时间点的日期),您可以始终使用固定时区(例如GMT)来显示日期。
NSDateFormatter
(用于向用户显示日期)也有一个timeZone
属性。An
NSDate
is an absolute point in time. When you want to know which day it falls on, you have to consider your specific time zone. Since you get theNSDateComponents
with anNSCalendar
, you can usesetTimeZone:
on the calendar to get the components (month, day, hour etc.) for the time zone you're interested in.If you deal with "calendar dates" (i.e. dates that should always represent a specific day/month and not an absolute point in time), you could always use a fixed time zone (e.g. GMT) to present the dates.
NSDateFormatter
(which you use for displaying dates to the user) also has atimeZone
property.在使用 NSCalendar 将日期分成几部分之前,您需要在 NSCalendar 中设置所需的时区:
You need to set the desired timezone in
NSCalendar
before using it to break the date into parts: