Objective-C NSDate 日付計算メモ


現在から1時間後を取得
[c]
[NSDate dateWithTimeIntervalSinceNow:60*60];
[/c]

基準時刻のNSDateから一時間後を取得
[c]
NSDate *baseDate = [NSDate date];
NSDate *afterOneHour = [now initWithTimeInterval:60*60 sinceDate:baseDate];
[/c]

今日の0:00を取得
[c]
NSDate *baseDate = [NSDate date];
NSCalendar * calendar = [NSCalendar currentCalendar];
NSUInteger flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit ;
NSDateComponents * components = [calendar components:flags fromDate:baseDate];
NSDate zeroTimeDate = [calendar dateFromComponents: components];
[/c]

今週の月曜日の日付を取得
[c]
NSDate *today = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit fromDate:date];
[components setWeekday:2]; //Monday
NSDate *monday = [calendar dateFromComponents:components];
[/c]

月初の日付を取得
[c]
NSDate *today = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components
= [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
fromDate:today];
components.day = 1;
NSDate *firstOfMonth = [calendar dateFromComponents:components];
[/c]

月の日数を取得
[c]
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *today = [NSDate date];
NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:today];
NSInteger daysOfMonth = rang.length;
[c]

日付を比較
[c]
NSDate *date1 = [NSDate date]; // 現在日付を取得
NSDate *date2 = [NSDate dateWithTimeIntervalSinceNow:1.0f]; // 現在日付 + 1秒
if ([date1 isEqualToDate:date2]) {
NSLog(@"同じ日付です");
} else {
NSLog(@"異なる日付です");
}
[/c]
逆引きObjective-C for iPhoneアプリ – 2つの日付を比較する

,