操纵日期

时间:2012-10-22 01:21:16

标签: objective-c ios nsdate

我是iOS的新手,在编写方法时我会遇到一些跟踪iOS模式的麻烦。我正在尝试使用objective-c找到一种在日期中增加值的简单方法。

考虑到:

NSInteger incrementType = 1; // from 1 to 4, days, weeks, months, year
NSInteger incrementSize = 20 // the increment size
NSDate* date = ... // some date

    +(NSDate*)somename:(NSInteger)incrementSize type:(NSInteger)incrementType current:(NSDate*)date {

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

        NSDateComponents* ateComponents = [[NSDateComponents alloc] init];
       // switch    
       [weekdayComponents setMonth:incrementSize];

        NSDate* newDate = [gregorian dateByAddingComponents:dateComponents toDate:date options:0];

        return newDate;

    }

问题:

  1. 我不确定逻辑是否正确。我在stackoverflow中找到了一段代码,我正在尝试修改它。
  2. 如何为incrementType参数编写枚举?
  3. 什么是好方法签名?。

1 个答案:

答案 0 :(得分:4)

之前我遇到了同样的挑战,我创建了一个简单的NSDate类别(使用ARC):

的NSDate + Utils.h:

@interface NSDate (Utils)

-(NSDate *)addDays:(NSInteger)days weeks:(NSInteger)weeks months:(NSInteger)months years:(NSInteger)years;

@end

的NSDate + Utils.m:

#import "NSDate+Utils.h"

@implementation NSDate (Utils)

-(NSDate *)addDays:(NSInteger)days weeks:(NSInteger)weeks months:(NSInteger)months years:(NSInteger)years {
    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
    [offsetComponents setDay:days];
    [offsetComponents setWeek:weeks];
    [offsetComponents setMonth:months];
    [offsetComponents setYear:years];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    return [calendar dateByAddingComponents:offsetComponents toDate:self options:0];
}

@end

我还创建了许多简单的方法,它们都调用上面的方法(在未使用的组件上使用零)。他们的签名是:

-(NSDate *)addDays:(NSInteger)days;
-(NSDate *)addWeeks:(NSInteger)weeks;
-(NSDate *)addMonths:(NSInteger)months;
-(NSDate *)addYears:(NSInteger)years;

addDays是这样的:

-(NSDate *)addDays:(NSInteger)days {
  return [self addDays:days weeks:0 months:0 years:0];
}

特别是,这些方法不需要incrementType枚举。