2012-02-24 3 views
3

NSDateNSCalendarが与えられている場合、指定された日付に続く1日の時間数はどのようにして決定されますか。次の日が夏時間(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)を参照してください。 –

答えて

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; 
関連する問題