码迷,mamicode.com
首页 > 其他好文 > 详细

与时间相关NSCalendar、NSDate类的基本使用

时间:2016-01-03 19:31:43      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

1.解决获取NSDate的时间不对

NSDate *nowDate = [NSDate date];
    
NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
NSInteger ti = [localTimeZone secondsFromGMTForDate:nowDate];
    
NSDate *newDate = [nowDate dateByAddingTimeInterval:ti];
NSLog(@"世界统一时间:%@ 当地时间:%@", nowDate, newDate);

 

 

 

1.获取当前时间的年月日时分秒

NSCalendar *calendar = [NSCalendar currentCalendar];

NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;

NSDateComponents *components = [calendar components:unit fromDate:[NSDate date]];

NSLog(@"年:%ld 月:%ld 日:%ld 时:%ld 分:%ld 秒:%ld",(long)components.year, (long)components.month, (long)components.day, (long)components.hour, (long)components.minute, (long)components.second);

 

 

2.比较两个时间之间的差值

NSDate *date1 = [NSDate date]; // 当前的日期

NSString *dateStr = @"2015-06-29 07:05:26 +0000";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss Z";
NSDate *date2 = [formatter dateFromString:dateStr];  // 指定的日期

NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *components = [calendar components:unit fromDate:date1 toDate:date2 options:0];

NSLog(@"相差年:%ld 月:%ld 日:%ld 时:%ld 分:%ld 秒:%ld",(long)components.year, (long)components.month, (long)components.day, (long)components.hour, (long)components.minute, (long)components.second);

 

与时间相关NSCalendar、NSDate类的基本使用

标签:

原文地址:http://www.cnblogs.com/dixuexiongying/p/5096874.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!