以编程方式获取日期“下周日下午5点”。 [英] Programmatically getting the date "next Sunday at 5PM"

查看:112
本文介绍了以编程方式获取日期“下周日下午5点”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

2013年8月7日编辑:Apple拥有一套优秀的WWDC视频,真正帮助我了解Objective-C中的各种日期和时间类,以及如何正确地执行时间计算/操作。

常见日期和时间挑战的解决方案(高清视频标清视频幻灯片(PDF))(WWDC 2013)

执行日历计算(< a href =https://developer.apple.com/videos/wwdc/2011/includes/performing-calendar-calculations.html#performing-calendar-calculations\"rel =nofollow>标清视频,< a href =https://developer.apple.com/devcenter/down load.action?path = / wwdc_2011 / adc_on_itunes__wwdc11_sessions__pdf / 117performing_calendar_calculations.pdfrel =nofollow> slide(PDF))(WWDC 2011)

"Solutions to Common Date and Time Challenges" (HD video, SD video, slides (PDF)) (WWDC 2013)
"Performing Calendar Calculations" (SD video, slides (PDF)) (WWDC 2011)

注意:链接需要免费的Apple开发者会员资格。

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

I'm writing an app for a friend's podcast. She broadcasts her show live every Sunday at 5PM, and I would like to write some code in my app to optionally schedule a local notification for that time, so that the user is reminded of when the next live show is. How would I go about getting an NSDate object that represents "the next Sunday, at 5 PM Pacific time." (obviously this would have to be converted into whatever timezone the user is using)

推荐答案

首先获取当周的当前日期:

First get the current day of the week:

NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

NSDateComponents *dateComponents = [calendar components:NSCalendarUnitWeekday | NSCalendarUnitHour fromDate:now];
NSInteger weekday = [dateComponents weekday];

Apple docs 将工作日定义为:


工作日单位是数字1到n,其中n是本周
天数。例如,在公历中,n为7,
星期日由1表示。

Weekday units are the numbers 1 through n, where n is the number of days in the week. For example, in the Gregorian calendar, n is 7 and Sunday is represented by 1.

接下来计算出有多少需要几天才能到达下一个周日5:

Next figure out how many days to add to get to the next sunday at 5:

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 到5:00。看看获取最新信息从[NSDate日期]开始计算日期,但将时间设置为上午10:00

To get it at 5:00 you can just change the hour and minute on nextSunday to 5:00. Take a look at get current date from [NSDate date] but set the time to 10:00 am

这篇关于以编程方式获取日期“下周日下午5点”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆