【问题标题】:Formatting a date for just the day number "dd"仅为日期编号“dd”格式化日期
【发布时间】:2014-01-06 16:40:19
【问题描述】:

我想从日期中获取日期。我有以下代码会产生不良输出:

NSDateFormatter* numDay = [[MSDateFormatter alloc]init];
numDay.dateFormat = @"DD";
dateString = [numDay stringFromDate:the_dte];
DayNum.text = [NSString stringWithFormat:@"%@", dateString];

例如,如果 the_dte2014-01-07,我会得到 dayNum38

我希望dayNum 改为持有 7。我认为这与我的格式有关。我只是不知道用什么格式来得到我想要的。

【问题讨论】:

  • 请参阅the documentation。对于月份中的某一天,请使用“d”或“dd”。 “DD”会让你一年中的某一天(虽然不知道为什么 7 号是 38 岁)。并且没有格式化程序代码来获取星期几 - 为此您需要使用 NSCalendarComponents。
  • 哇。那很简单。谢谢。
  • 为该网站添加书签——它会为您节省数小时的时间。
  • Hot Licks 再次击败了我。讨厌你! (干得好。)

标签: ios nsdateformatter date-format


【解决方案1】:

在您的示例中,the_dte 应该是 NSDate。如果是这种情况,那么我认为您应该阅读this answer to get exactly what you are looking for

基本上你可以通过

从 NSDate 中获取日期组件
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:the_dte];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];

然后使用 NSString 的 stringWithFormat: 将这些组件格式化为您想要的任何字符串,并将其分配给您的标签文本

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 2015-09-23
    • 1970-01-01
    相关资源
    最近更新 更多