问题
NSDate *dateNow = [NSDate date];
NSLog(@"NSDate : %@", dateNow);
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];
NSString *dateString = [dateFormatter stringFromDate:dateNow];
NSLog(@"NSDateFormatter String: %@", dateString);
NSDate *dateObject = [dateFormatter dateFromString:dateString];
NSLog(@"NSDateFormatter Object: %@", dateObject);
First off ignore the 1970-01-01 I am only interested in the time for now.
My question is when I get the time from NSDate it does not include any time zone information. This is what I expected so the time returned from NSDate is 01:21:57 PM. To correct this I am using NSDateFormatter and setting its locale, it correctly interprets that I am in London, British Summer Time (GMT+01). Finally I want to get the new corrected date back as an NSDate so I use dateFromString on the previously correct dateString.
Can anyone tell me why the resultant date reverts back to being uncorrected (i.e. 01:21:57 PM) is there anyway that I can do this conversion and still maintain the specified locale / timeZone?
>> WALL_CLOCK: 02:21:57 PM
>> NSDate : 2011-04-08 01:21:57 PM +0000
>> NSDateFormatter String: 02:21:57 PM GMT+01:00
>> NSDateFormatter Object: 1970-01-01 01:21:57 PM +0000
回答1:
All NSDate objects are stored as seconds since the reference date (Jan 1 2001 00:00 GMT) and so are always GMT+0.
回答2:
In your code. You only provided the format for the Locale and Time. You didn't provide a format for the Date, therefore you got the default result: 1970-01-01
NSDate *dateNow = [NSDate date];
NSLog(@"NSDate : %@", dateNow);
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
NSString *dateString = [dateFormatter stringFromDate:dateNow];
NSLog(@"NSDateFormatter String: %@", dateString);
NSDate *dateObject = [dateFormatter dateFromString:dateString];
NSLog(@"NSDateFormatter Object: %@", dateObject);
Output:
2011-04-08 10:12:39.119 test[2957:207] NSDate : 2011-04-08 14:12:39 +0000
2011-04-08 10:12:39.121 test[2957:207] NSDateFormatter String: April 8, 2011 10:12:39 AM EDT
2011-04-08 10:12:39.123 test[2957:207] NSDateFormatter Object: 2011-04-08 14:12:39 +0000
来源:https://stackoverflow.com/questions/5595848/nsdateformatter-to-nsstring