首页 > 代码库 > NSDate(NSCalendar,NSDateComponents,NSDateFormatter)

NSDate(NSCalendar,NSDateComponents,NSDateFormatter)

-1 NSString 转成 NSDate

    NSString *time = @"2014-05-18 09:24:40";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *date = [dateFormatter dateFromString:time];
    NSLog(@"%@",date);

-2 获取本地时间 (将格林威治时间转换成本地时间)

    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:date];
    NSDate *localeDate = [date dateByAddingTimeInterval:interval];
    NSLog(@"%@",localeDate);

-3 将 NSDate 转成 NSString

    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss Z";//"Z"表示时区
    NSString *currentDate = [dateFormatter stringFromDate:date];
    NSLog(@"%@",currentDate);

  使用  NSDateFormatter 会自动将时间转换成本地时间输出

-4 使用 NSCalendar 和 NSDateComponents 获取时间要素

    NSDate *date = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *dateComponents = [calendar components:unit fromDate:date];
    NSLog(@"现在时间是%li年%li月%li天%li小时%li分钟%li秒", dateComponents.year, dateComponents.month, dateComponents.day, dateComponents.hour, dateComponents.minute, dateComponents.second);

-5 比较两个时间的时间差(这里以格林威治时间和本地时间做示例)

    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:date];
    NSDate *localeDate = [date dateByAddingTimeInterval:interval];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *dateComponents = [calendar components:unit fromDate:date toDate:localeDate options:0];
    
    NSLog(@"格林威治时间和本地时间相差%ld年%ld月%ld天%ld小时%ld分钟%ld秒", dateComponents.year, dateComponents.month, dateComponents.day, dateComponents.hour, dateComponents.minute, dateComponents.second);