2012-02-24 17 views
3

给定NSDateNSCalendar,如何确定指定日期之后当天的小时数。取决于下一天是进入夏令时(23),正常(24)还是现在的夏令时(25),这将是23,24或25。确定给定日期(加或减DST班次小时数)的小时数

+0

看一看[“确定时域的区别”(https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtCalendricalCalculations.html#//apple_ref/doc/uid/TP40007836-SW8)的日期和时间编程指南。 – 2012-02-24 19:32:28

回答

3

你可以问日历中的任意单元有多长(和单位开始时)与rangeOfUnit:startDate:interval:forDate:

// Test date (the day DST begins) 
NSDateComponents *components = [[NSDateComponents alloc] init]; 
components.year = 2012; 
components.month = 3; 
components.day = 11; 

NSCalendar *calendar = [NSCalendar currentCalendar]; 
NSDate *date = [calendar dateFromComponents:components]; 
NSTimeInterval dayLength; 
[calendar rangeOfUnit:NSDayCalendarUnit startDate:NULL interval:&dayLength forDate:date]; 
NSLog(@"%f seconds", dayLength); 

注意rangeOfUnit:...可以techincally失败并返回NO,但如果控制不应该是能够发生的输入。

2
// Test input 
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
formatter.dateFormat = @"yyyy MM dd HH:mm:ss"; 
NSDate *referenceDate = [formatter dateFromString:@"2012 03 24 13:14:14"]; 

// Get reference date with day precision 
NSCalendar *calendar = [NSCalendar currentCalendar]; 
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; 
NSDateComponents *components = [calendar components:unitFlags fromDate:referenceDate]; 

NSDate *today = [calendar dateFromComponents:components]; 

// Set components to add 1 day 
components = [[NSDateComponents alloc] init]; 
components.day = 1; 

// The day after the reference date 
NSDate *tomorrow = [calendar dateByAddingComponents:components toDate:today options:0]; 

// The day after that 
NSDate *afterTomorrow = [calendar dateByAddingComponents:components toDate:tomorrow options:0]; 

// Difference in hours: 23, 24 or 25 
NSUInteger hours = [afterTomorrow timeIntervalSinceDate:tomorrow]/3600; 
相关问题