日期格式更改自2013-12-30T14:59:00。+ 0000

时间:2014-01-15 10:17:18

标签: nsdateformatter

我有一个来自服务器的日期格式为2013-12-30T14:59:00。+ 0000我想将其转换为格式MMM dd,yyyy h:mm a

我在做如下

NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
[dateFormatter setTimeZone:timeZone];
NSDate *dateFromString = [dateFormatter dateFromString:selectedDate];
if (dateFromString != nil) 
{
       [dateFormatter setDateFormat:@"MMM dd,yyyy h:mm a"];
       stringDateFromDate = [dateFormatter stringFromDate:dateFromString];
}

但是“dateFromString”为零。

任何人都可以帮助

1 个答案:

答案 0 :(得分:0)

在我看来,提出建议为时已晚。但我决定写。

请参阅此示例了解selectedDate字符串并执行以下操作:

NSString *selectedDate = @"2013-12-30T14:59:00.+0000";

// I donno what "T" means, that's just replace it to an empty string
selectedDate = [selectedDate stringByReplacingOccurrencesOfString:@"T" withString:@" "];

// get string without .+0000
NSRange range = [selectedDate rangeOfString:@"."];
selectedDate = [selectedDate substringToIndex:range.location];

NSString *stringDateFromDate;

NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
[dateFormatter setTimeZone:timeZone];

// necessarily set this date format!
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *dateFromString = [dateFormatter dateFromString:selectedDate];

if (dateFromString != nil)
{
[dateFormatter setDateFormat:@"MMM dd,yyyy h:mm a"];
stringDateFromDate = [dateFormatter stringFromDate:dateFromString];
}

// That's all. Output your string.
NSLog(@"%@", stringDateFromDate);