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

Categories

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

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

1 Answer

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"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...