问题描述
如何将以下日期Sun Jul 17 07:48:34 +0000 2011
转换为以下格式2011-07-17 07:48:34?
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"?
我使用 NSDateFormatter
,如下所示,但它没有用。结果为null。
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];
推荐答案
你的日期格式错误了您传入的日期。以下是解释不同修饰符的文档:
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
要解析日期Sun Jul 17 07:48:34 +0000 2011,您需要这样的格式:
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"];
要使其符合以下格式:2011-07-17 07:48:34,这是完整的代码:
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];
这篇关于转换目标C中的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!