确定 NSDate 对象的日期组成部分(时区问题)

发布于 2024-11-29 14:25:18 字数 103 浏览 5 评论 0原文

我如何确定某个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

川水往事 2024-12-06 14:25:18

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 the NSDateComponents with an NSCalendar, you can use setTimeZone: 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 a timeZone property.

Spring初心 2024-12-06 14:25:18

在使用 NSCalendar 将日期分成几部分之前,您需要在 NSCalendar 中设置所需的时区:

NSCalendar* gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
[gregorian setTimeZone:[NSTimeZone localTimeZone]]; // or timeZoneWithName:@"GMT" etc.

unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
NSDateComponents* compsDate = [gregorian components:unitFlags fromDate:date];
// [compsDate year] [compsDate month] [compsDate day] 

You need to set the desired timezone in NSCalendar before using it to break the date into parts:

NSCalendar* gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
[gregorian setTimeZone:[NSTimeZone localTimeZone]]; // or timeZoneWithName:@"GMT" etc.

unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
NSDateComponents* compsDate = [gregorian components:unitFlags fromDate:date];
// [compsDate year] [compsDate month] [compsDate day] 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文