ios-日期获取

2016-12-06  本文已影响39人  IMKel

获取当前时间

// 获取当前时间(即格林尼治时间)
    NSDate *nowDate = [NSDate date];
    NSLog(@"nowDate = %@", nowDate);

获取本地时间,即北京时间

// 获取本地时间(北京时间) 28800秒 == 8小时
    NSDate *localDate = [[NSDate alloc] initWithTimeIntervalSinceNow:28800];
    NSLog(@"localDate = %@", localDate);

附加知识:

日期转字符串(NSDate-->NSString)

// 获取本地时间(北京时间) 28800秒 == 8小时
    NSDate *localDate = [[NSDate alloc] initWithTimeIntervalSinceNow:28800];
// 打印本地时间,NSDate类型
    NSLog(@"localDate = %@", localDate);
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:localDate];
// 打印本地时间,NSString类型
    NSLog(@"dateString = %@", dateString);

字符串转日期(NSString-->NSDate)

    NSString *dateString = @"2016-12-06 11:28:29 8";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss z"];
    NSDate *date = [dateFormatter dateFromString:dateString];
    NSLog(@"date = %@", date);

获取NSDate中的年/月/日等等

// 通过日期组件对象获取日期某一部分,不需要给日期加8小时就能获取本地时间.这让笔者感到困惑.
//    获取当前时间(格林尼治时间)
    NSDate *localDate = [NSDate date];
    
// 创建日期组件对象
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];

// 创建日历对象
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
// 给日期组件对象赋值
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    dateComponents = [calendar components:unitFlags fromDate:localDate];
    
    NSLog(@"localDate = %@", localDate);
    NSLog(@"%ld", dateComponents.year);
    NSLog(@"%ld", dateComponents.month);
    NSLog(@"%ld", dateComponents.day);
    NSLog(@"%ld", dateComponents.hour);
    NSLog(@"%ld", dateComponents.minute);
    NSLog(@"%ld", dateComponents.second);
上一篇下一篇

猜你喜欢

热点阅读