NSDate - 获取一个月中的几天(而不是一年中的几天)?

发布于 01-02 14:44 字数 501 浏览 3 评论 0原文

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

例如,我的 NSDate 可能是 5 月 16 日。我希望能够获得这一天,因此它返回 16。即该月的第 16 天(而不是该年的第 16 天)。

谢谢。

编辑:

我有这个:

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

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

Using NSDateComponents I know how to get the day component, but this gives me a value from 1 - 365, right? I need to get the days 1-30 of a specific month, how can I?

For example, I have an NSDate which might be 16th May. I want to be able to get the day, so it returns 16. Being the 16th day of that month (not the 16th day of the year).

Thanks.

EDIT:

I have this:

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

However comps.day returns 1 when it should equal what the date is saved as, say 4.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

み青杉依旧2025-01-09 14:44:04

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 天。

The day value of NSDateComponents gives you the day of month according to the given calendar:

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

gives

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

although February, 4th would be the 35th day of the year.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文