Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

iphone - Converting a date format in objective C

How can i convert the following date "Sun Jul 17 07:48:34 +0000 2011" to the following format "2011-07-17 07:48:34"?

I used NSDateFormatter as shown below but it didnt work. It gives null as a result.

NSDateFormatter *objDateFormatter = [[NSDateFormatter alloc] init];
[objDateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[objDateFormatter dateFromString:sDate];
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You've got your Date Format wrong for the style of Date you are passing in. Here is a document explaining the different modifiers: Date Format Patterns

To parse the Date "Sun Jul 17 07:48:34 +0000 2011", you'd need a Format like so:

[dateFormat setDateFormat:@"EEE MMM dd HH:mm:ss ZZZ yyyy"];

To get it into the following format: "2011-07-17 07:48:34", here is the full code:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss ZZZ yyyy"];
NSDate *date  = [dateFormatter dateFromString:sDate];

// Convert to new Date Format
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *newDate = [dateFormatter stringFromDate:date]; 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...