【问题标题】:NSDate - Getting Days of the Month (Not Days of the year)?NSDate - 获取每月的日子(不是一年中的日子)?
【发布时间】:2012-02-04 14:08:16
【问题描述】:

使用 NSDateComponents 我知道如何获取日期组件,但这给了我一个 1 到 365 之间的值,对吧?我需要获取特定月份的第 1-30 天,我该怎么做?

例如,我有一个可能是 5 月 16 日的 NSDate。我希望能够得到这一天,所以它返回 16。作为该月的第 16 天(不是一年中的第 16 天)。

谢谢。

编辑:

我有这个:

NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [cal components:NSDayCalendarUnit fromDate:[[NSUserDefaults standardUserDefaults] objectForKey:@"dateSaved"]];

但是当 comps.day 应该等于保存的日期时返回 1,比如 4。

【问题讨论】:

  • 只是为了确定:尝试 NSLog comps,以及您从默认值中检索到的日期对象。
  • 我已经 NSLogged 他们,comps.day 总是返回 1,我无法记录保存的日期,我该如何正确?我试过NSLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"dateSaved"]); 我在控制台中得到空值。但是我知道它不会返回 null,因为我在其他地方使用它并从中设置日期并且它可以工作。
  • 您确定密钥是正确的并且您在代码中的正确时间调用它吗?这似乎表明您没有得到正确的 NSDate 对象。
  • 我非常专注于其他事情,这正是我错过的,感谢您睁开眼睛。

标签: iphone objective-c nsdate nsdatecomponents


【解决方案1】:

NSDateComponentsday 值根据给定的日历为您提供月份中的日期:

NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:NSDayCalendarUnit fromDate:date];
NSLog(@"%@ / %d", date, comps.day);

给予

2012-02-04 15:27:36.682 testapp[1533:f803] 2012-02-04 14:27:36 +0000 / 4

虽然 2 月 4 日是一年中的第 35 天。

【讨论】:

  • 已编辑答案并附有回复,希望您能提供帮助。
猜你喜欢
  • 2011-04-11
  • 2012-02-12
  • 1970-01-01
  • 2011-12-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-02
  • 1970-01-01
相关资源
最近更新 更多