ios開発–NSDateとNSCalendarの使い方

1.NSDateの利用方法
NSDate *now = [NSDate date];
NSLog(@"%@",now);

//now+20秒
NSDate *now1 = [now dateByAddingTimeInterval:20];
NSLog(@"%@",now1);

//システムのタイムゾーンを取得
NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
NSLog(@"timeZone = %@",timeZone);

//現在のゾーンと指定ゾーンの時刻差
NSInteger seconds =[timeZone secondsFromGMTForDate:now];
NSLog(@"seconds = %ld",seconds);

//時間フォーマット
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd hh-mm-ss Z";

//String -> date
NSString *now1 = @"2016-05-14 03:16:28 +0011″;
NSLog(@"%@",[formatter dateFromString:now1]);
NSDate *now = [NSDate date];

2. NSCalendarの利用方法
NSCalendar *calender = [NSCalendar currentCalendar];
NSCalendarUnit type = NSCalendarUnitYear |
NSCalendarUnitMonth |
NSCalendarUnitDay |
NSCalendarUnitHour |
NSCalendarUnitMinute |
NSCalendarUnitSecond;
NSDateComponents *cmps = [calender components:type fromDate:now];
NSLog(@"year = %ld", cmps.year);
NSLog(@"month = %ld", cmps.month);
NSLog(@"day = %ld", cmps.day);
NSLog(@"hour = %ld", cmps.hour);
NSLog(@"minute = %ld", cmps.minute);
NSLog(@"second = %ld", cmps.second);

//時間比較
NSString *str = @"2015-05-21 07:05:26 +0000″;
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss Z";
NSDate *date = [formatter dateFromString:str];
//現在の時間を取得
NSDate *now1 = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *component1 = [calendar components:type fromDate:date toDate:now1 options:0];
NSLog(@"%ld年%ld月%ld日%ld時%ld分%ld秒", component1.year, component1.month, component1.day, component1.hour, component1.minute, component1.second);

IOS

Posted by arkgame