现在的位置: 首页 > 综合 > 正文

17,Objective-C Foundation框架中的NSDate

2014年06月07日 ⁄ 综合 ⁄ 共 1470字 ⁄ 字号 评论关闭

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

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

抱歉!评论已关闭.