0
我想知道現在和下一個星期三14:00之間的差異。計算直到iOS中給定時間點的時間
我發現[NSDate date];
給我的當前時間和日期,以及一個NSTimeInterval
通常被用於此目的(我想在其他地方使用這個區間,和別的地方想一個NSTimeInterval),所以代碼將如下所示:
NSDate *now = [NSDate date];
NSDate *nextWednesday = ???;
// profit
NSTimeInterval secondsUntilNextWednesday = [nextWednesday timeIntervalSinceDate:now];
但是,如何得到下一個星期三的日期?編輯2:我改進了方法,我仍然非常不喜歡它,但這是一個巨大的進步。此外,它更讓人想起我的僞裝嘗試。
- (NSTimeInterval)secondsUntilNextWednesday
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *today = [NSDate date];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate: today];
// 17 == 15:00, seemingly. (timezones)
[components setHour:17];
[components setWeekday:4];
NSDate *wednesday = [calendar dateFromComponents:components];
NSTimeInterval secondsToWednesday = [wednesday timeIntervalSinceDate:today];
// if secondsToWednesday is negative, it has already been wednesday, 15:00 (or 16:00 depending on DST)
if (secondsToWednesday < 0)
{
secondsToWednesday += 604800;
}
return secondsToWednesday;
}