NSDateFormatter giving me time 4 hours ahead

核能气质少年 提交于 2019-12-04 16:42:19

When you NSLog an NSDate it will print the time as a GMT time zone In order to see the correct data you will have to convert the NSDate to string using stringFromDate

NSDate *dateFromString = [[[NSDate alloc] init]autorelease];

NSLog(@"DATE %@", _date);

//Instead of nslog directly, use this stringFromDate:remindOn
NSString *str = [formatter stringFromDate:dateFromString];
NSLog(@"date is %@", str); //This will log the correct data

The problem you are getting is not in the NSDate but it is in Logging it UPDATE In order to save the data to a file or database i would suggest that you save it like this

NSTimeInterval timeInterval  = [dateFromString timeIntervalSince1970];

Now when you read it again from the database you would do

NSDate *data = [[NSDate alloc] initWithTimeIntervalSince1970:timeInterval]

The following code will show your time with your time zone:

NSString *_date = @"Jun 11, 2012 9:30 PM";

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];    
NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];

[formatter setDateFormat:@"MMMM dd, yyyy h:mma"];  
[formatter2 setDateFormat:@"MMMM dd, yyyy h:mma Z"];  

NSDate *dateFromString = [[NSDate alloc] init];

NSLog(@"DATE %@", _date);

dateFromString = [formatter dateFromString:_date];

NSLog(@"NSDATEFROMSTRING %@", dateFromString);
NSLog(@"NSDATEFROMSTRING %@", [formatter stringFromDate:dateFromString]);
NSLog(@"NSDATEFROMSTRING %@", [formatter2 stringFromDate:dateFromString]);

Result:

DATE Jun 11, 2012 9:30 PM
NSDATEFROMSTRING 2012-06-12 04:30:00 +0000
NSDATEFROMSTRING June 11, 2012 9:30PM
NSDATEFROMSTRING June 11, 2012 9:30PM -0700

If you Google for UTC Time now, it does give you a time that is close to the second line in the output, which confirms it is printing out the time as a UTC time.

(We are in different time zone and dateFromString is interpreting the time in the string as your local time.)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!