NSDate 时区设置 及转换

先说下自己开发过程中之前迷惑的两点:

1 unix 时间戳使用 p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Menlo; color: #3495af}span.s1 {font-variant-ligatures: no-common-ligatures}

NSDateFormatter 进行转换时,会自动转换为当前时区的时间。
2 字符串的类型的时间,如“2016-01-01”,系统会默认为是当前时区的时间,转换为NSDate时是0时区的 。

自已定义的转换方法
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Menlo; color: #008f00}p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Menlo}p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Menlo; color: #3495af}p.p4 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Menlo; min-height: 14.0px}p.p5 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px 'PingFang SC'; color: #008f00}span.s1 {font-variant-ligatures: no-common-ligatures}span.s2 {font: 12.0px 'PingFang SC'; font-variant-ligatures: no-common-ligatures}span.s3 {font-variant-ligatures: no-common-ligatures; color: #3495af}span.s4 {font-variant-ligatures: no-common-ligatures; color: #0433ff}span.s5 {font-variant-ligatures: no-common-ligatures; color: #000000}span.s6 {font-variant-ligatures: no-common-ligatures; color: #b4261a}span.s7 {font: 12.0px Menlo; font-variant-ligatures: no-common-ligatures; color: #000000}span.s8 {font: 12.0px Menlo; font-variant-ligatures: no-common-ligatures}

// serverTime 为标准时间戳

  • (NSString *)dateStringWithServerTime:(double)serverTime
    {
    return [self dateStringWithServerTime:serverTime withForm:@"yyyy-MM-dd HH:mm:ss"];
    }

//

  • (NSString *)dateStringWithServerTime:(double)serverTime withForm:(NSString *)form
    {
    // date 是0时区的时间
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:serverTime];

    // 系统会默认转化为东八区时间
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:form];
    NSString *dateStr = [dateFormatter stringFromDate:date];
    return dateStr;
    }

// serverTime 为标准时间戳

  • (NSTimeInterval)secondsWithDateString:(NSString *)dateString withForm:(NSString *)form
    {
    //系统会认为字符串是东八区的时间, 转乘NSDate是零时区的

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:form];
    NSDate *date = [dateFormatter dateFromString:dateString];

// //将转换回来的对象手动加上8小时,回到北京时间
// NSDate *date2 = [date dateByAddingTimeInterval:8 * 60 * 60];
// // 添加默认系统时差 为当前时间
// NSTimeInterval interVal = [[NSTimeZone defaultTimeZone] secondsFromGMTForDate:[NSDate date]];
// NSDate *date3 = [date dateByAddingTimeInterval:interVal];

return [date timeIntervalSince1970];

}

//

  • (NSTimeInterval)secondsWithDateString:(NSString *)dataString
    {
    return [self secondsWithDateString:dataString withForm:@"yyyy-MM-dd HH:mm:ss"];
    }

// 获取 当前0时区的日期 serverTime 为标准时间戳

  • (NSDate *)dateWithSeconds:(double)serverTime
    {
    return [NSDate dateWithTimeIntervalSince1970:serverTime];
    }

参考文章:http://www.jianshu.com/p/df41659b06a9

你可能感兴趣的:(NSDate 时区设置 及转换)