如何获取相对日期

发布于 2024-10-24 07:57:19 字数 85 浏览 1 评论 0原文

如何在 Objective-C 中获取相对日期?

如果我有“今天”,我如何找到“昨天”,“上周”,“最后两周”,“一个月前”,“两个月前”?

how can I get relative dates in Objective-C?

If I have "today", how do I find "yesterday", "last week", "last two weeks", "one month ago", "two months ago"?

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

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

发布评论

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

评论(1

傲影 2024-10-31 07:57:19

因此,如果您有 NSDate *today = [NSDate date];,那么您可以使用 NSDateComponents 获取相对日期。

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *today = [NSDate date];

NSDateComponents *yesterdayComponents = [[NSDateComponents alloc] init];
[yesterdayComponents setDay:-1];
NSDate *yesterday = [calendar dateByAddingComponents:yesterdayComponents toDate:today options:0];
[yesterdayComponents release];

NSDateComponents *twoWeeksAgoComponents = [[NSDateComponents alloc] init];
[twoWeeksAgoComponents setWeek:-2];
NSDate *twoWeeksAgo = [calendar dateByAddingComponents:twoWeeksAgoComponents toDate:today options:0];
[twoWeeksAgoComponents release];

等等。

NSDateComponentsNSCalendar 自动处理下溢和溢出(除非您使用 options: 位将其关闭)。因此,如果今天是“2 月 28 日”而您想要“明天”,它会根据年份自动选择“2 月 29 日”或“3 月 1 日”。非常酷。这也是进行日期操作的唯一正确方法

So if you have an NSDate *today = [NSDate date];, then you can use NSDateComponents to get relative dates.

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *today = [NSDate date];

NSDateComponents *yesterdayComponents = [[NSDateComponents alloc] init];
[yesterdayComponents setDay:-1];
NSDate *yesterday = [calendar dateByAddingComponents:yesterdayComponents toDate:today options:0];
[yesterdayComponents release];

NSDateComponents *twoWeeksAgoComponents = [[NSDateComponents alloc] init];
[twoWeeksAgoComponents setWeek:-2];
NSDate *twoWeeksAgo = [calendar dateByAddingComponents:twoWeeksAgoComponents toDate:today options:0];
[twoWeeksAgoComponents release];

Etc.

NSDateComponents and NSCalendar handle underflowing and overflowing automatically (unless you turn it off with the options: bit). So if today is "28 February" and you want "tomorrow", it will automatically choose either "29 February" or "1 March" depending on the year. It's pretty cool. This is also the only proper way of doing date manipulation.

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