首页 > 其他 > 详细

17,Objective-C Foundation框架中的NSDate

时间:2014-02-21 03:48:03      阅读:367      评论:0      收藏:0      [点我收藏+]

获取时间、考虑时区、时间格式

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    //获取当前时间
    NSDate *now = [NSDate date];
    NSLog(@"It‘s %@ now,",now);
    
    //获取距离某个时间点的时间
    NSDate *then = [[NSDate alloc] initWithTimeInterval:3600 sinceDate:now];
    NSLog(@"after 3600 second:%@",then);
    
    //考虑时区
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:now];
    NSDate *localDate = [now dateByAddingTimeInterval:interval];
    NSLog(@"the local date is %@",localDate);
    
    //时间格式
    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 *date = [dateFormatter stringFromDate:[NSDate date]];
    NSLog(@"年月日 date = %@",date);
    
    [dateFormatter setDateFormat:@"hh:mm:ss"];
    NSString *time = [dateFormatter stringFromDate:[NSDate date]];
    NSLog(@"时间 time = %@",time);
}

日期的比较
01 /*----日期时间的比较----*/
02         // 当前时间
03         NSDate *currentDate = [NSDate date];
04          
05         // 比当前时间晚一个小时的时间
06         NSDate *laterDate = [[NSDate alloc] initWithTimeInterval:60*60 sinceDate:[NSDate date]];
07          
08         // 比当前时间早一个小时的时间
09         NSDate *earlierDate = [[NSDate alloc] initWithTimeInterval:-60*60 sinceDate:[NSDate date]];
10          
11         // 比较哪个时间迟
12         if ([currentDate laterDate:laterDate]) {
13             // 打印结果:current-2013-08-16 09:25:54 +0000比later-2013-08-16 10:25:54 +0000晚
14             NSLog(@"current-%@比later-%@晚",currentDate,laterDate);
15         }
16          
17         // 比较哪个时间早
18         if ([currentDate earlierDate:earlierDate]) {
19             // 打印结果:current-2013-08-16 09:25:54 +0000 比 earlier-2013-08-16 08:25:54 +0000
20             NSLog(@"current-%@ 比 earlier-%@ 早",currentDate,earlierDate);
21         }
22          
23         if ([currentDate compare:earlierDate]==NSOrderedDescending) {
24             // 打印结果
25             NSLog(@"current 晚");
26         }
27         if ([currentDate compare:currentDate]==NSOrderedSame) {
28             // 打印结果
29             NSLog(@"时间相等");
30         }
31         if ([currentDate compare:laterDate]==NSOrderedAscending) {
32             // 打印结果
33             NSLog(@"current 早");
34         }


17,Objective-C Foundation框架中的NSDate

原文:http://blog.csdn.net/isharestudio/article/details/19544159

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!