当我从我的Xcode iPhone模拟器转换时间时,我的代码工作正常,输出显示在这里:
2014-02-12 18:11:52 +0000
当地时区(欧洲/伦敦(GMT)抵消0)
0
但是当我尝试在iPhone 5上使用我的应用程序时,输出更改为
1970-01-01 12:00:00 am +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];
}
谢谢,
答案 0 :(得分:1)
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);
答案 1 :(得分:0)
愿这个扩展更容易。
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)")