确定给定日期的小时数(加上或减去DST班次小时)

时间:2012-02-24 18:03:02

标签: objective-c cocoa

鉴于NSDateNSCalendar,如何确定指定日期之后一天的小时数。这将是23,24或25,具体取决于第二天是进入夏令时(23),正常(24)还是退出夏令时(25)。

2 个答案:

答案 0 :(得分: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:...可以在技术上失败并返回NO,但是如果你控制了不应该发生的输入。

答案 1 :(得分: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;