NSDateComponents
的需求来简化日期操作。NSDateComponents
转换为 NSDictionary
表示形式,以便快速使用。如果您想使用除 [NSCalendar currentCalendar]
之外的日历,则所有方法都有一个类似的版本,可以传递一个 NSCalendar
。
Dash 的 Docset
而不是这个
NSDate *now = [NSDate date];
// Create components to shift date by 5 years
NSDateComponents *comps = [NSDateComponents new];
[comps setYear:5];
NSDate *fiveYearsFromNow = [[NSCalendar currentCalendar] dateByAddingComponents:comps toDate:now options:0];
可以替换为
NSDate *now = [NSDate date];
NSDate *fiveYearsFromNow = [now dateByUsingCurrentCalendarToAdjustCalendarUnit:NSYearCalendarUnit withValue:5];
这还演示了使用字典表示形式快速创建日期组件。而不是这个
NSDate *now = [NSDate date];
// Create components to shift date by 1 year, 7 months, 15 hours, 36 seconds
NSDateComponents *comps = [NSDateComponents new];
[comps setYear:1];
[comps setMonth:7];
[comps setHour:15];
[comps setSecond:36];
NSDate *adjustedDate = [[NSCalendar currentCalendar] dateByAddingComponents:comps toDate:now options:0];
可以替换为
NSDate *now = [NSDate date];
// Create components to shift date by 1 year, 7 months, 15 hours, 36 seconds
NSDictionary *compsDict = @{@(NSYearCalendarUnit) : 1,
@(NSMonthCalendarUnit) : 7,
@(NSHourCalendarUnit) : 15,
@(NSSecondCalendarUnit) : 36};
NSDate *adjustedDate = [now dateByUsingCurrentCalendarToAddDateComponentsDictionary:compsDict];
也可以简化创建组件的过程
// To get a NSDateComonents object
NSDateComponents *comps = [NSDateComponents dateWithCurrentCalendarFromDateComponentsDictionary:@{@(NSYearCalendarUnit) : 1,
@(NSMonthCalendarUnit) : 7,
@(NSHourCalendarUnit) : 15,
@(NSSecondCalendarUnit) : 36}];
// To go from NSDateComponents
NSDictionary *compsDict = [comps dictionaryRepresentation];
而不是这个
// Components for 2001-01-01, UTC+2
NSDateComponents *comps = [NSDateComponents new];
[comps setYear:2001];
[comps setMonth:1];
[comps setDay:1];
[comps setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:2 * 3600]];
NSDate *date = [[NSCalendar currentCalendar] dateFromComponents:comps];
可以替换为
NSDate *date = [NSDate dateWithCurrentCalendarFromDateComponentsDictionary:@{
@(NSYearCalendarUnit) : @2001,
@(NSMonthCalendarUnit) : 1,
@(NSDayCalendarUnit) : 1,
@(NSTimeZoneUnit) : [NSTimeZone timeZoneForSecondsFromGMT:2 * 3600]}];
而不是这个
NSCalendar *cal = [NSCalendar currentCalendar];
// Remove time component
NSDateComponents *comps = [cal componentsFromDate:[NSDate date]];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
NSDate *date = [cal dateFromComponents:comps];
可以替换为
NSDate *date = [[NSDate date] dateOfStartOfDayUsingCurrentCalendar];