【问题标题】:How to get relative dates如何获取相对日期
【发布时间】:2011-07-19 20:22:22
【问题描述】:

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

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

【问题讨论】:

  • 真的不知道你在问什么。

标签: objective-c relative-date


【解决方案1】:

因此,如果您有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 日”。它太酷了。这也是进行日期操作的唯一正确方法

【讨论】:

  • 未正确返回的周数 NSDateComponents *TwoWeeksAgoComponents = [components copy]; [TwoWeeksAgoComponents setWeek:[TwoWeeksAgoComponents week]-2]; NSDate *TwoWeeksAgo = [日历日期FromComponents:TwoWeeksAgoComponents]; NSLog([格式化字符串FromDate:TwoWeeksAgo]); [TwoWeeksAgoComponents 发布];
  • NSCalendar 也依赖于 ipad 日历,或者它总是乔治亚
  • 这段代码不起作用;它总是返回初始日期。我不得不使用dateByAddingComponents:toDate:options:。我假设对这个答案的所有支持都来自没有实际测试代码的人。
  • @titaniumdecoy 我已经更新了代码。现在应该可以正常工作了。
  • @DaveDeLong 谢谢。我删除了我的答案,因为它现在与你的重复。
猜你喜欢
  • 2019-09-11
  • 2020-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-15
  • 2016-01-10
相关资源
最近更新 更多