[英]Converting string to NSDate, timezones do not adjust correctly?
我正在尝试将一个时间字符串从一个时区转换为NSDate对象,然后使用本地时区将其输出回字符串。 但是我似乎要出去1小时。 例如,我在输出时区中添加了代码,以便显示错误。 有一些类似的问题,但没有任何提示可以告诉我我在哪里出错了!!! 发布时,这两个时区目前都处于夏令时-但是NSDateFormatter应该注意基于时区的任何差异。
更新:问题似乎在于将洛杉矶时间转换为格林尼治标准时间,而不是转换为BST。 据我所知,所有NSDate都存储为GMT。 下面的代码演示了这一点(添加了语言环境-似乎没有什么不同):
NSDateFormatter *dateF = [[NSDateFormatter alloc] init];
[dateF setDateFormat:@"HH:mm"];
[dateF setTimeZone:[NSTimeZone timeZoneWithName:@"America/Los_Angeles"]];
[dateF setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
NSDate* sourceDate = [dateF dateFromString:@"09:15"];
NSLog(@"Date GMT: %@", [sourceDate description]);
NSLog(@"Date BST: %@", [sourceDate descriptionWithLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"]]);
输出:
日期GMT:1970-01-01 17:15:00 +0000 这是不正确的!
日期BST:1970年1月1日,星期四,18:15:00 GMT + 01:00, 所以这也不正确
原始示例
洛杉矶的09:15应该是伦敦的17:15,而不是18:15 ...
NSDateFormatter *dateF = [[NSDateFormatter alloc] init];
[dateF setDateFormat:@"HH:mm"];
[dateF setTimeZone:[NSTimeZone timeZoneWithName:@"America/Los_Angeles"]];
NSDate* sourceDate = [dateF dateFromString:@"09:15"];
NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
[dateformatter setDateFormat:@"HH:mm"];
[dateformatter setTimeZone:[NSTimeZone timeZoneWithName:@"Europe/London"]];
NSLog(@"%@", [dateformatter stringFromDate:sourceDate]);
NSDate对象以绝对时间存储日期。 例如,清单16中创建的date对象表示CDT 4:00 PM,EDT 5:00等。
NSCalendar *gregorian=[[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CDT"]];
NSDateComponents *timeZoneComps=[[NSDateComponents alloc] init];
[timeZoneComps setHour:16];
//specify whatever day, month, and year is appropriate
NSDate `enter code here`*date=[gregorian dateFromComponents:timeZoneComps];
从NSTimeZone文档:
请注意,严格来说,时区数据库条目(例如“ America / Los_Angeles”)是ID而非名称。 时区名称的示例是“太平洋夏令时间”。 尽管许多NSTimeZone方法名称都包含单词“ name”,但它们引用的是ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.