Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

iphone - How to handle different date time formats using NSDateFormatter

I have a String with a datetime format: "YYYY-MM-DD HH:MM:SS".

I use this in my source code:

NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"%e. %B %Y"];
NSString *test = [formatter stringFromDate:@"2010-01-10 13:55:15"];

I want to convert from "2010-01-10 13:55:15" to "10. January 2010". But my implementation does not work.

What's wrong here?

Thanks a lot in advance & Best Regards.

Updated source code:

[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"%Y-%m-%d %H:%M:%S"];
NSString *test1 = [formatter stringFromDate:@"2010-01-10 13:55:15"];

NSDateFormatter *formatter1 = [[[NSDateFormatter alloc] init] autorelease];
[formatter1 setDateFormat:@"%d. %M4 %Y"];
NSString *test2 = [formatter1 stringFromDate:test1];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A date formatter can only handle one format at a time. You need to take this approach:

NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [f dateFromString:@"2010-01-10 13:55:15"];

NSDateFormatter *f2 = [[NSDateFormatter alloc] init];
[f2 setDateFormat:@"d. MMMM YYYY"];
NSString *s = [f2 stringFromDate:date];

s will now be "10. January 2010"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...