开发者

NSDateFormater dateFromString:

NSDateFormatter *isoDateFormatter = [NSDateFormatter new];
[isoDateFormatter setDateFormat:@"yyyy-MM-dd"];
[isoDateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
[isoDateFormatter s开发者_运维技巧etFormatterBehavior:NSDateFormatterBehaviorDefault];
NSString * str = [isoDateFormatter dateFromString:@"2008-12-31T12:00:00"]

on 4.0 IOS the above code i.e str is nill, on 3.0 IOS this works fine str is 2008-12-31. How to overcome this issue?


It looks like you want to convert a date from one string format to another. To do that, you have to have to do it in two steps--formatting FROM string to NSSDate, then from that date to NSString.

NSDateFormatter *dateWriter = [[NSDateFormatter alloc] init];
NSDateFormatter *dateReader = [[NSDateFormatter alloc] init];
[dateWriter setDateFormat:@"yyyy-MM-dd"];
[dateReader setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];

NSDate *dateTmp = [dateReader dateFromString:@"2008-12-31T12:00:00"];
NSString *str = [dateWriter stringFromDate:dateTmp]
//str now contains "2008-12-31". 

//and don't forget!!!
[dateReader release];
[dateWriter release];

You could achieve the same result with one date formatter by reading, resetting the dateFormat and then writing, if you want. I just laid it out like this so it's easy to see the process.

Side note--I'm always forgetting to release NSDateFormatters. Clang and Instruments are always catching me leaking them. I guess I use them and it feels like they're done. They're not, though! So be smarter than me and remember to NARC on your memory management!

Side note 2--Don't ignore compiler warnings. Your compiler is warning you about the invalid assignment you're doing, and you're ignoring that.


dateFromString: Returns a date representation of a given string interpreted using the receiver’s current settings.

- (NSDate *)dateFromString:(NSString *)string

Parameters string The string to parse. Return Value A date representation of string interpreted using the receiver’s current settings.

Availability Available in iOS 2.0 and later. See Also

– getObjectValue:forString:range:error:
– stringFromDate:

Related Sample Code URLCache Declared In

NSDateFormatter.h

Read the docs.

The dateFromString returns an Date object not an NSString.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜