17,Objective-C Foundation框架中的NSDate

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

- (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         }


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值