iOS NSDate and NSDateFormatter behavior
So, I have a String with the format YYMMDDHHMMSS, and I'm trying (hard) to get a proper NSDate object from it.
This is my code:
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[format setDateFormat:@"yyMMddHHmmss"];
NSDate *date = [format dateFromString:@"140904123421"];
NSLog(@"DATE: %@", date);
And I'm getting weird times like this:
DATE: 2014-09-04 17:04:21 +0000
I've checked this table and my formatters seem right, I also tried removing the locale, but I still got wrong dates. So, is it possible to get back the right time?
Thanks.
As pointed out in the comments on your question, your NSDate
is correct; NSDate
always stores its time in GMT
. By default, when NSDateFormatter
parses your date it converts it from your local time zone to GMT
so that what's stored in the resulting NSDate
object is consistent (it's actually more nuanced than that, but you can think of it that way). Since your time zone is GMT-04:30
that means it's going to add 4 hours and 30 minutes to your time, making 2014-09-04 12:34:21 GMT-4:30
= 2014-09-04 17:04:21 GMT
(as @MartinR pointed out).
From your comments, it sounds like you need to store this date in your database in the format yyyy-MM-dd HH:mm:ss
, in local time . The easiest way to do that is to simply use a second NSDateFormatter
:
NSDateFormatter *formatOut = [[NSDateFormatter alloc] init];
[formatOut setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *dateString = [formatOut stringFromDate: date];
Since NSDateFormatter
will use your local time zone by default, that should "convert" date
from GMT
back to GMT-4:30
and set dateString
to 2014-09-04 12:32:21
.
All that being said, storing a date in your local time zone is almost always a bad idea . Time zones are tricky things, so it's best to always store and do any calculations on your date in GMT
/ UTC
, then only convert it to local time when you're displaying it to your user. This will save you a lot of pain if someone outside your time zone accesses your data, your time zone rules change (happens more often than you might think), you need to pass your date to some external service/app, etc.
上一篇: F#默认值中的依赖项属性不匹配