IOS工具

iOS中UTC/GMT时间与地时区时间 转换总结

2017-10-25  本文已影响42人  Console_Liu
/**
 anyDate 转成 本地时区的 NSDate
 */
- (NSDate *)getLocalDateFormatAnyDate:(NSDate *)anyDate {
    NSTimeZone *sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];//或GMT
    NSTimeZone *desTimeZone = [NSTimeZone localTimeZone];
    //得到源日期与世界标准时间的偏移量
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:anyDate];
    //目标日期与本地时区的偏移量
    NSInteger destinationGMTOffset = [desTimeZone secondsFromGMTForDate:anyDate];
    //得到时间偏移量的差值
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    //转为现在时间
    NSDate* destinationDateNow = [[NSDate alloc] initWithTimeInterval:interval sinceDate:anyDate];
    return destinationDateNow;
}
/**
 将本地日期字符串转为UTC日期字符串
 eg: 2017-10-25 02:07:39 -> 2017-10-24 18:07:39
 */
- (NSString *)getUTCStrFormateLocalStr:(NSString *)localStr {
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    format.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *dateFormatted = [format dateFromString:localStr];
    format.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    NSString *dateString = [format stringFromDate:dateFormatted];
    return dateString;
}
/**
 将UTC日期字符串转为本地时间字符串
 eg: 2017-10-25 02:07:39  -> 2017-10-25 10:07:39
 */
- (NSString *)getLocalDateFormateUTCDate:(NSString *)utcStr {
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    format.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    format.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    NSDate *utcDate = [format dateFromString:utcStr];
    format.timeZone = [NSTimeZone localTimeZone];
    NSString *dateString = [format stringFromDate:utcDate];
    return dateString;
}
上一篇下一篇

猜你喜欢

热点阅读