以编程方式获得“下周五下午5点”的date

编辑07/08/13:苹果有一套非常棒的WWDCvideo,这些video确实帮助我理解Objective-C中的各种date和时间类,以及如何正确执行时间计算/操作。

“共同的date和时间挑战的解决scheme”( 高清video , 标清video , 幻灯片(PDF) )(WWDC 2013)
“执行日历计算”( SDvideo , 幻灯片(PDF) )(WWDC 2011)

注意:链接需要免费的Apple Developer会员。

我正在为一个朋友的播客写一个应用程序。 她每个星期天下午5点播放她的节目,我想在我的应用程序中编写一些代码,以便有select地安排当地的通知,以便提醒用户下次现场演出的时间。 我将如何去获得一个代表“下个星期日太平洋时间下午5点”的NSDate对象。 (显然这必须转换成用户使用的任何时区)

首先获取当周的当天:

NSDate *now = [NSDate date]; NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; NSDateComponents *dateComponents = [calendar components:NSCalendarUnitWeekday | NSCalendarUnitHour fromDate:now]; NSInteger weekday = [dateComponents weekday]; 

苹果文档定义一个工作日为:

平日单位是数字1到n,其中n是一周中的天数。 例如,在公历中,n是7,星期天是1。

接下来要弄清楚要在5点到下一个星期天才能添加多less天。

 NSDate *nextSunday = nil; if (weekday == 1 && [dateComponents hour] < 5) { // The next Sunday is today nextSunday = now; } else { NSInteger daysTillNextSunday = 8 - weekday; int secondsInDay = 86400; // 24 * 60 * 60 nextSunday = [now dateByAddingTimeInterval:secondsInDay * daysTillNextSunday]; } 

要在5:00得到它,你可以改变下一个nextSunday的小时和分钟。 看看从[NSDatedate]获得当前date,但设置时间为上午10:00