简体   繁体   English

NSDateFormatter,NSDate,UTC和奇怪的日期格式

[英]NSDateFormatter, NSDate, UTC and strange date format

I have a very strange date format coming to me via JSON. 我有一个非常奇怪的日期格式通过JSON来找我。 eg - "July, 18 2010 02:22:09" 例如 - “July,18 2010 02:22:09”

These dates are always UTC. 这些日期始终为UTC。 I'm parsing the date with NSDateFormatter, and setting the timeZone to UTC... 我正在使用NSDateFormatter解析日期,并将timeZone设置为UTC ...

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
[inputFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];
[inputFormatter setDateFormat:@"MMMM, dd yyyy HH:mm:ss"];
NSDate *formatterDate = [inputFormatter dateFromString:dtStr];

However, the date when logged is appearing with the offset of my device... 但是,记录的日期与我的设备的偏移量一起出现...

"2010-07-18 02:22:09 -0600" “2010-07-18 02:22:09 -0600”

What am I doing wrong here? 我在这做错了什么?

I think this is because your NSDate isn't using the UTC timezone. 我认为这是因为你的NSDate没有使用UTC时区。 The docs say this about the description method of NSDate: 文档说这是关于NSDate的描述方法:

A string representation of the receiver in the international format YYYY-MM-DD HH:MM:SS ±HHMM, where ±HHMM represents the time zone offset in hours and minutes from GMT (for example, “2001-03-24 10:45:32 +0600”). 接收器的字符串表示形式,国际格式为YYYY-MM-DD HH:MM:SS±HHMM,其中±HHMM表示从GMT开始的小时和分钟的时区偏移(例如,“2001-03-24 10:45” :32 +0600“)。

So, you aren't really doing anything wrong. 所以,你真的没有做错任何事。 NSDate is behaving as expected. NSDate的行为符合预期。 What are you trying to accomplish? 你想达到什么目的? Do you need the date in a string? 你需要字符串中的日期吗? Are you doing date comparison? 你在做日期比较吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM