【问题标题】:Objective-C: Subtract 100 years from now [duplicate]Objective-C:从现在减去 100 年 [重复]
【发布时间】:2014-01-24 14:29:31
【问题描述】:

我现在如何从 NSDate 中减去 100 年?

我有这个:

NSDate *now = [NSDate date];
NSDate *hundredYearsAgo = [now dateByAddingTimeInterval:100*365*24*60*60];

但这并没有考虑到有 365 天的年份和有 366 天的年份。

【问题讨论】:

  • 你研究过NSDateComponents吗?

标签: objective-c nsdate


【解决方案1】:

使用NSCalendarNSDateComponents 进行日期计算。

unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
NSDate *now = [NSDate date];
NSCalendar *gregorian = [NSCalendar currentCalendar];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:now];
[comps setYear:[comps year] - 100];
NSDate *hundredYearsAgo = [gregorian dateFromComponents:comps];

然后观看这个视频,解释为什么你不应该自己进行日期计算:
The Problem with Time & Timezones - Computerphile

【讨论】:

  • 只有我还是@DavidRönnqvist 的回答更准确?您正在从组件中剥离时间,从而导致与日期的巨大偏移。
【解决方案2】:

你真的应该使用 NSCalendar 和 NSDateComponents 来进行这样的计算,因为它们会变得非常棘手并且可能充满烦人的边缘情况。

如果您使用 NSCalendar 和 NSDateComponents(如下面的代码),它将为您处理所有事情,例如闰年。

NSDate *now = [NSDate date];
NSDateComponents *minusHundredYears = [NSDateComponents new];
minusHundredYears.year = -100;
NSDate *hundredYearsAgo = [[NSCalendar currentCalendar] dateByAddingComponents:minusHundredYears
                                                                        toDate:now
                                                                       options:0];

如果您想对该主题进行一些额外的阅读,我已经在 Objective-C 中写过关于 working with dates 的文章。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 2017-08-04
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多