一、NSDate初始化
-
- NSDate *date = [NSDate date];
-
-
-
-
-
- NSLog(@"当前时间 date = %@",date);
-
-
-
-
-
- date = [[NSDate alloc] initWithTimeInterval:60 sinceDate:[NSDate date]];
-
-
-
-
-
- NSLog(@"当前时间 往后60s的时间date = %@",date);
PS:测试时时间是下午5点,但是得到的当前时间却是上午9点,相差了8小时,是时区的问题
解决办法:
- NSTimeZone *zone = [NSTimeZone systemTimeZone];
-
-
-
- NSInteger interval = [zone secondsFromGMTForDate: date];
-
-
-
- NSDate *localDate = [date dateByAddingTimeInterval: interval];
-
-
-
-
-
- NSLog(@"正确当前时间 localDate = %@",localDate);
二、NSDate与NSString的转换
-
- NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];
-
-
-
-
-
- [dateFormatter setDateFormat:@"年月日 YYYY/mm/dd 时间 hh:mm:ss"];
-
-
-
- NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
-
-
-
-
-
- NSLog(@"dateString = %@",dateString);
-
-
-
-
-
-
-
- [dateFormatter setDateFormat:@"YYYY-MM-dd"];
-
-
-
- NSString *year = [dateFormatter stringFromDate:[NSDate date]];
-
-
-
-
-
- NSLog(@"年月日 year = %@",year);
-
-
-
-
-
- [dateFormatter setDateFormat:@"hh:mm:ss"];
-
-
-
- NSString *time = [dateFormatter stringFromDate:[NSDate date]];
-
-
-
-
-
- NSLog(@"时间 time = %@",time);
三、日期的比较
-
-
-
- NSDate *currentDate = [NSDate date];
-
-
-
-
-
- NSDate *laterDate = [[NSDate alloc] initWithTimeInterval:60*60 sinceDate:[NSDate date]];
-
-
-
-
-
- NSDate *earlierDate = [[NSDate alloc] initWithTimeInterval:-60*60 sinceDate:[NSDate date]];
-
-
-
-
-
- if ([currentDate laterDate:laterDate]) {
-
-
-
- NSLog(@"current-%@比later-%@晚",currentDate,laterDate);
-
- }
-
-
-
-
-
- if ([currentDate earlierDate:earlierDate]) {
-
-
-
- NSLog(@"current-%@ 比 earlier-%@ 早",currentDate,earlierDate);
-
- }
-
-
-
- if ([currentDate compare:earlierDate]==NSOrderedDescending) {
-
-
-
- NSLog(@"current 晚");
-
- }
-
- if ([currentDate compare:currentDate]==NSOrderedSame) {
-
-
-
- NSLog(@"时间相等");
-
- }
-
- if ([currentDate compare:laterDate]==NSOrderedAscending) {
-
-
-
- NSLog(@"current 早");
-
- }
NSDate简单使用
原文:http://www.cnblogs.com/ranger-jlu/p/3955132.html