【问题标题】:Converting NSDate using the NSDateFormatter使用 NSDateFormatter 转换 NSDate
【发布时间】:2014-04-27 11:07:47
【问题描述】:

我有一组日期为NSStrings。它们采用下一种格式: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;
}

【问题讨论】:

  • 书签this date format page,你以后会用到的!
  • 我认为您的意思是公历而不是格鲁吉亚,这不是一种格式 - 它是一个日历系统。您可以以任何您喜欢的方式格式化公历日期。我还怀疑,如果您使用正确的方法,您将不需要自己替换月份名称。

标签: ios nsdate nsdateformatter


【解决方案1】:

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

【讨论】:

  • @user1665325,你能描述一下unformatted字符串的样子吗? formattedDate 字符串应该是什么样子?
  • 未格式化的格式为:1980/9/26 17:23:00 或 1980/12/26 17:23:00。格式化日期将采用波斯日历形式。问题是月份可能是两位数或一位数。日期格式化程序要么用 M 检测一位数字,要么用 MM 检测两位数字。
  • @user1665325,我更新了我的答案。现在它应该可以工作了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-08
  • 1970-01-01
  • 1970-01-01
  • 2012-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多