当我从Xcode iPhone模拟器转换时间时,我的代码工作正常,输出如下所示:
2014-02-12 18:11:52 +0000
本地时区(欧洲/伦敦 (GMT) 偏移量 0)
0
但是当我尝试在iPhone 5上使用我的应用程序时,输出更改为
1970-01-01 12:00:00 上午 +0000
本地时区(欧洲/伦敦 (GMT) 偏移量 0)
0
我正在使用 Xcode 5.0 和 iOS 7
-(NSDate *)convertGMTtoLocal:(NSString *)gmtDateStr {
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSTimeZone *gmt = [NSTimeZone systemTimeZone];
[formatter setTimeZone:gmt];
NSDate *GMTTime = [formatter dateFromString:gmtDateStr];
NSTimeZone *tz = [NSTimeZone localTimeZone];
NSLog(@"%@",tz);
NSInteger seconds = [tz secondsFromGMTForDate: GMTTime];
NSLog(@"%ld",(long)seconds);
NSLog(@"%@",[NSDate dateWithTimeInterval: seconds sinceDate: GMTTime]);
return [NSDate dateWithTimeInterval: seconds sinceDate: GMTTime];
}
谢谢
NSLog 以 GMT 记录日期。不要使用它。创建一个日期格式化程序并使用它来记录您的日期。另一个海报的代码完全是反向的,并将日期转换为 GMT。在vborra的代码中省略setTimeZone调用,它应该会给你本地时间的日期。
代码可能如下所示:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterNoStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
NSString *time = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"Time is %@", time);
愿这个扩展会更容易。
Swift 4:UTC/GMT ⟺ 本地(当前/系统)
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)
}
}
// Try it
let utcDate = Date().toGlobalTime()
let localDate = utcDate.toLocalTime()
print("utcDate - (utcDate)")
print("localDate - (localDate)")