簡體   English   中英

使用NSDateFormatter轉換NSDate

[英]Converting NSDate using the NSDateFormatter

我有一組日期作為NSString s。 它們采用下一種格式: 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;
}

你需要使用MM幾個月。 此外,您需要使用HH幾個小時。 試試這種格式: yyyy/MM/dd HH:mm:ss

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM