2011-02-18 26 views
4

我想知道这是此日期格式Friday, December 18th,也是该标准的日期格式或我有一些艰苦的工作得到这个。这是本NSDateFormatter风格周五,12月18日

谢谢。

+0

看看[这个要点](https://gist.github。COM/JigsChanchiya/6044680#文件suffixdate毫米)。 – cjd 2014-02-15 11:26:58

回答

8

我不认为可以通过格式化来实现。虽然你可以做这样的:

NSDate *today = [NSDate date]; 
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"EEEE, MMMM d"]; 
    NSString *dateString = [dateFormat stringFromDate:today]; 
    NSCalendar *cal = [NSCalendar currentCalendar]; 
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; 
    NSDateComponents *dtComp = [cal components:unitFlags fromDate:today]; 
    switch ([dtComp day]) { 
     case 1: 
     case 31: 
     case 21: 
      dateString = [dateString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%i",[dtComp day]] withString:[NSString stringWithFormat:@"%ist",[dtComp day]]]; 
      break; 
     case 2: 
     case 22: 
      dateString = [dateString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%i",[dtComp day]] withString:[NSString stringWithFormat:@"%ind",[dtComp day]]]; 
       break; 
     case 3: 
     case 23: 
      dateString = [dateString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%i",[dtComp day]] withString:[NSString stringWithFormat:@"%ird",[dtComp day]]]; 
      break; 
     default: 
      dateString = [dateString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%i",[dtComp day]] withString:[NSString stringWithFormat:@"%ith",[dtComp day]]]; 
      break; 
    } 

    [dateFormat release]; 
+0

我不知道谁低估了我的答案,但我很快意识到我的错误。 +1给你指出第一个后缀! – BoltClock 2011-02-18 13:27:17

3

@Robin Help with NSDateFormatter在这种情况下会帮助你很多NSDateFormatter,你真的必须努力获得这种格式,只需看看我与你分享的链接。

祝你好运!

+0

感谢的人。对此,我真的非常感激。谢谢 – Robin 2011-02-18 16:12:41

3

如果有可能以可读的方式我会在Madhups回答评论张贴长注释。

因此,这里是我的评论:

与这些自定义日期格式的坏事是,如果你从美国或使用相同的日期格式其他国家都没有的日期是错误的。

这就是你的解决方案将如何看待我的设备:Freitag,Februar 18日
我的母亲会说th?那是什么意思?

我会说“另一位从未离开过他的国家的开发者。”

我想我的约会对象是这样的:Freitag的,18 Februar

,因为这是我已经习惯了。这是一个约会的样子。

所以请添加只使用自定义日期格式化,如果当前区域是DATEFORMAT您正在使用类似的定制的支票。


在iOS4中,Apple引入了一个非常酷的方法。

+ (NSString *)dateFormatFromTemplate:(NSString *)template options:(NSUInteger)opts locale:(NSLocale *)locale

你通过这个方法,你在你的日期格式希望每一个部件,你回来使用的语言环境的格式。

所以,如果你想使用的工作日中,日,月,你会使用这样的:

NSString *localizedDateFormat = [NSDateFormatter dateFormatFromTemplate:@"EEEE MMMM d" options:0 locale:[NSLocale currentLocale]]; 

,它会返回EEEE, d. MMMM为德语语言环境。或者美国区域的EEEE, MMMM d。然后你可以使用它来设置一个自定义的dateFormat。

这就是NSDateFormatter的重点。本地化日期。如果您使用[dateFormatter setDateFormat:@"some hard coded date format"]向用户显示日期,则在大多数情况下您做错了。

我真的很讨厌那个混美国日期风格和德国的日期风格的应用程序。

相关问题