使用NSDateFormatter转换NSDate

时间:2014-04-27 11:07:48

标签: ios nsdate nsdateformatter

我有一组日期NSString。它们采用下一种格式:1980/9/26 17:23:00。问题是月份从1到9的月份不包括零。所以有些日期是1980/9/26 17:23:00,有些是1980/12/26 17:23:00。日期格式化程序获得yyyy/mm/dd hh:mm:ssyyyy/m/dd hh:mm:ss

无论我使用哪两种格式,我都无法格式化这两种日期类型。这是我使用的代码:

-(NSString *) convertDate : (NSString *) unformatted
{

//Format the Date
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy/mm/dd hh:mm:ss"];

NSDate *date = [dateFormat dateFromString:unformatted];

//Format the Calendar
NSDateFormatter *f = [[NSDateFormatter alloc] init];
NSCalendar *persian = [[NSCalendar alloc] initWithCalendarIdentifier:@"persian"];
[f setCalendar:persian];
[f setDateStyle:NSDateFormatterLongStyle];

NSString *formattedDate = [f stringFromDate:date];
//Replace english strings with farsi strings
formattedDate=[formattedDate stringByReplacingOccurrencesOfString:@"Farvardin" withString:@"فروردین"];
formattedDate=[formattedDate stringByReplacingOccurrencesOfString:@"Ordibehesht" withString:@"اردیبهشت"];
formattedDate=[formattedDate stringByReplacingOccurrencesOfString:@"Khordad" withString:@"خرداد"];
formattedDate=[formattedDate stringByReplacingOccurrencesOfString:@"Tir" withString:@"تیر"];
formattedDate=[formattedDate stringByReplacingOccurrencesOfString:@"Mordad" withString:@"مرداد"];
formattedDate=[formattedDate stringByReplacingOccurrencesOfString:@"Shahrivar" withString:@"شهریور"];
formattedDate=[formattedDate stringByReplacingOccurrencesOfString:@"Mehr" withString:@"مهر"];
formattedDate=[formattedDate stringByReplacingOccurrencesOfString:@"Aban" withString:@"آبان"];
formattedDate=[formattedDate stringByReplacingOccurrencesOfString:@"Azar" withString:@"آذر"];
formattedDate=[formattedDate stringByReplacingOccurrencesOfString:@"Dey" withString:@"دی"];
formattedDate=[formattedDate stringByReplacingOccurrencesOfString:@"Bahman" withString:@"بهمن"];
formattedDate=[formattedDate stringByReplacingOccurrencesOfString:@"Esfand" withString:@"اسفند"];
formattedDate=[formattedDate stringByReplacingOccurrencesOfString:@"AP" withString:@""];

return formattedDate;
}

1 个答案:

答案 0 :(得分:3)

您需要使用MM数月。此外,您需要使用HH几个小时。请尝试以下格式:yyyy/MM/dd HH:mm:ss