54.9K views | +3 today
panda/ios dev/@aceisScope on github
Curated by Bertie Liu
Your new post is loading...
Your new post is loading...
Scooped by Bertie Liu!


CupertinoYankee | PandaLit |
CupertinoYankee - An NSDate Category With Locale-Aware Calculations for Beginning & End of Day, Week, Month, and Year
Bertie Liu's insight:

By godlike Matt

No comment yet.
Scooped by Bertie Liu!

Safe Way to Convert NSString and NSDate

Normally if we need to convert NSString to NSDate, a NSDateFormatter is necessary.

It may appear like this, @"EEE MMM d H:m:s Z y", which may represent "Mon Mar 12 11:46:08 +0800 2012". The letters may seem a bit confusing.

Here is a good reference:  ;

After we are clear about how to set a NSDateFormatter, the next step is to convert any string representing the date we need to NSDate, then convert the NSDate we get with another formatter  to the NSString with the final format.


the function may appear like this below:

-(NSString *)LocalDateFromServerDate:(NSString *)string
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:WEIBO_DATEFORMAT];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSDate *date = [formatter dateFromString:string];

[formatter setDateFormat:LOCAL_DATEFORMAT];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *localDate = [formatter stringFromDate:date];
[formatter release];

return localDate;

 Notice that no matter what the timezone may be in the original string,  "Mon Mar 12 11:46:08 +0800 2012" or "Mon Mar 12 11:46:08 +0000 2012" or any other, just make sure the  first formatter used for convert it to NSDate should be setTimeZone to GMT. This might be a necessity for a correct result for the NSDate, which is used as the base for further convertion.


 If none of those above work or only work on simulator not device, the add this:

formatter.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease];    before calloing dateFromString



No comment yet.