iOS开发交流平台iOS开发札记iOS Developer

NSSting 与 NSDate 时间戳 恩怨情仇

2016-04-07  本文已影响162人  小布走慢点

NSSting 转 NSDate

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSDate *date = [dateFormatter dateFromString:resultString];

NSDate 转 NSString

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];

获取本地 NSDate

    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    NSInteger interval = [timeZone secondsFromGMTForDate: date];
    NSDate *localeDate = [date dateByAddingTimeInterval: interval];

时区转换

    NSDateFormatter *Formatter = [[NSDateFormatter alloc] init];
    [Formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [Formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    NSString *strDate = [Formatter stringFromDate:localeDate];
    NSLog(@"%@", strDate);

NSDate 转时间戳

NSDate *date = [NSDate date];
NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];

时间戳转 NSDate

NSDate *date = [NSDate date];
NSTimeInterval  timeInterval = [date timeIntervalSince1970]-1800;//前30分钟
NSDate *newdate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
上一篇 下一篇

猜你喜欢

热点阅读