简体   繁体   English

使用NSDateFormatter转换NSDate

[英]Converting NSDate using the NSDateFormatter

I have a set of dates as NSString s. 我有一组日期作为NSString s。 They are in the next format: 1980/9/26 17:23:00 . 它们采用下一种格式: 1980/9/26 17:23:00 The problem is that the month doesn't include a zero for months from 1 to 9. So some of the dates are 1980/9/26 17:23:00 and some are 1980/12/26 17:23:00 . 问题是月份从1到9不包括零个月。所以有些日期是1980/9/26 17:23:00 ,有些是1980/12/26 17:23:00 The date formatter either gets a yyyy/mm/dd hh:mm:ss or yyyy/m/dd hh:mm:ss . 日期格式化程序得到yyyy/mm/dd hh:mm:ssyyyy/m/dd hh:mm:ss

Whichever of these two formats I use, I can't format both date types. 无论我使用这两种格式,我都无法格式化这两种日期类型。 Here is the code I used by the way: 这是我使用的代码:

-(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;
}

You need to use MM for months. 你需要使用MM几个月。 Also, you need to use HH for hours. 此外,您需要使用HH几个小时。 Try this format: yyyy/MM/dd HH:mm:ss . 试试这种格式: yyyy/MM/dd HH:mm:ss

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM