NSDate - 一年前,进退两难

Cod*_*Guy 5 iphone objective-c nsdate nscalendar ios

我正在尝试做一些对我来说有点困难的事情.但我确信有人有一些见解.

比如约会,January 17, 2011我试图弄清楚一年前与这个日期相对应的日期.所以January 17, 2011是一个星期一,一年前,这一天就下跌January 18, 2010(星期一一样).结果January 18, 2010是354天前January 17, 2011.我原本以为简单地减去非闰年365天和闰年366天,但如果你这样做,你会得到January 17, 2010,这是星期日,而不是星期一.

所以,在Objective-C中使用NSDateNSCalendar,我如何实现如下函数:

-(NSDate *)logicalOneYearAgo:(NSDate *)from {
}
Run Code Online (Sandbox Code Playgroud)

换句话说,第n个月的第n个"工作日"(其中"工作日"是星期一或星期二或星期三等)

gra*_*rks 22

您可以像这样使用NSDateComponents:

- (NSDate *)logicalOneYearAgo:(NSDate *)from {

    NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

    NSDateComponents *offsetComponents = [[[NSDateComponents alloc] init] autorelease];
    [offsetComponents setYear:-1];

    return [gregorian dateByAddingComponents:offsetComponents toDate:from options:0];

}
Run Code Online (Sandbox Code Playgroud)


Max*_*eod 11

"日历和时间编程指南"部分中的"日历计算"," 将组件添加到日期"中对此进行了介绍

具体来说,感兴趣的方法是dateByAddingComponents:toDate:options.

使用Apple示例作为基础,从当前日期减去一年,您将执行以下操作:

NSDate *today = [[NSDate alloc] init];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

/*
  Create a date components to represent the number of years to add to the current date.
  In this case, we add -1 to subtract one year.     
*/

NSDateComponents *addComponents = [[NSDateComponents alloc] init];
addComponents.year = - 1;

return [calendar dateByAddingComponents:addComponents toDate:today options:0];
Run Code Online (Sandbox Code Playgroud)


Cod*_*Guy -8

答案其实很简单。事实证明这是经过反复试验的。答案如下。

如果年份是闰年,则减去 365 天。

如果该年份不是闰年,则减去 364 天。