如何将UTC日期字符串转换为本地时间(系统时区)

12

输入的字符串:June 14, 2012 - 01:00:00 UTC

本地输出字符串:Jun 13, 2012 - 21:00:00 EDT

我想获取偏移量。

NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSLog(@"Time Zone: %@", destinationTimeZone.abbreviation);
任何建议?
5个回答

23

这应该可以满足你的需求:

NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"LLL d, yyyy - HH:mm:ss zzz";
NSDate *utc = [fmt dateFromString:@"June 14, 2012 - 01:00:00 UTC"];
fmt.timeZone = [NSTimeZone systemTimeZone];
NSString *local = [fmt stringFromDate:utc];
NSLog(@"%@", local);

请注意,你的示例是不正确的:当世界标准时间为6月14日上午1点时,在美国东部时间区(EST)仍然是6月13日晚上8点标准时间或9点夏令时。在我的系统上,此程序打印:

Jun 13, 2012 - 21:00:00 EDT

6

Swift 3

var dateformat = DateFormatter()
dateformat.dateFormat = "LLL d, yyyy - HH:mm:ss zzz"
var utc: Date? = dateformat.date(fromString: "June 14, 2012 - 01:00:00 UTC")
dateformat.timeZone = TimeZone.current
var local: String = dateformat.string(from: utc)
print(local)


Swift 4: 日期扩展UTC或GMT ⟺ 本地时间

//UTC or GMT ⟺ Local 

extension Date {

    // Convert local time to UTC (or GMT)
    func toGlobalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

    // Convert UTC (or GMT) to local time
    func toLocalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

}

3
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"MMMM d, yyyy - HH:mm:ss zzz"; // format might need to be modified

NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
[dateFormatter setTimeZone:destinationTimeZone];

NSDate *oldTime = [dateFormatter dateFromString:utcDateString];

NSString *estDateString = [dateFormatter stringFromDate:oldTime];

1

这是将GMT时间转换为本地时间的代码,您可以稍作修改以适用于UTC时间。

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm";

NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; 
[dateFormatter setTimeZone:gmt]; 
NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]]; 
[dateFormatter release];

取自iPhone: NSDate将GMT转换为本地时间


0
func timeConverter() -> 
{
    let zone = TimeZone.current
    let sec = -TimeInterval(zone.secondsFromGMT(for: self)
    return Date(timeInterval: sec , since : self)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接