简体   繁体   中英

NSDateFormatter to NSString?

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 (ie 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

自参考日期(2001年1月1日00:00 GMT)以来,所有NSDate对象都存储为秒,因此始终为GMT + 0。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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