【问题标题】:How To Add Ordinal Abbreviations Format To Date In iOS e.g. "th" , "st" [duplicate]如何在 iOS 中添加序号缩写格式到日期,例如“th”,“st” [重复]
【发布时间】:2013-02-12 19:01:43
【问题描述】:

我有以下代码将我的日期和时间格式化为字符串,例如:

2013 年 10 月 25 日星期一 - 14:56:34

NSDate *today = [[NSDate alloc] init];
dateFormatter = [[NSDateFormatter alloc] init];
[self.dateFormatter setDateFormat:@"EEEE, MMMM dd YYYY - HH:mm:ss"];

NSString *currentTime = [self.dateFormatter stringFromDate: today];
self.timerLabel.text = currentTime.uppercaseString;

效果很好。但是如何将“th”或“rd”或“st”适当地放在日期,即上面示例中的 25 之后?

【问题讨论】:

  • 这很容易。只需拨打NumberFormatter.localizedString(from: 1, number: .ordinal) // 1st

标签: ios date nsdate


【解决方案1】:
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"MMMM dd"];

NSDate *now = [[NSDate alloc] init];

NSString *dateString = [format stringFromDate:[now dateByAddingTimeInterval:(-60*60*24*10)]];
NSMutableString *tempDate = [[NSMutableString alloc]initWithString:dateString];
int day = [[tempDate substringFromIndex:[tempDate length]-2] intValue];
switch (day) {
    case 1:
    **case 21:
    case 31:**
        [tempDate appendString:@"st"];
        break;
    case 2:
    **case 22:**
        [tempDate appendString:@"nd"];
        break;
    case 3:
    **case 23:**
        [tempDate appendString:@"rd"];
        break;
    default:
        [tempDate appendString:@"th"];
        break;
}
NSLog(@"%@",tempDate);

【讨论】:

  • 有本地化的方法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-11
  • 1970-01-01
  • 2020-04-01
  • 2011-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多