iOS計算某個日期n個月之後的日期
阿新 • • 發佈:2019-02-13
如題。
畫個圖分析一下:
程式碼
- (NSDate *)dateAfterMonths:(NSDate *)currentDate gapMonth:(NSInteger)gapMonthCount {
//獲取當年的月份,當月的總天數
NSCalendar *calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitCalendar fromDate:currentDate];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateStyle:NSDateFormatterFullStyle];
[formatter setDateFormat:@"yyyy-MM-dd" ];
// [formatter setTimeZone:[NSTimeZone localTimeZone]];
// [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Shanghai"]];
NSString *dateStr = @"";
NSInteger endDay = 0;//天
NSDate *newDate = [NSDate date];//新的年&月
//判斷是否是下一年
if (components.month+gapMonthCount > 12) {
//是下一年
dateStr = [NSString stringWithFormat:@"%zd-%zd-01",components.year+(components.month+gapMonthCount)/12,(components.month+gapMonthCount)%12];
newDate = [formatter dateFromString:dateStr];
//新月份的天數
NSInteger newDays = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:newDate].length;
if ([self isEndOfTheMonth:currentDate]) {//當前日期處於月末
endDay = newDays;
} else {
endDay = newDays < components.day?newDays:components.day;
}
dateStr = [NSString stringWithFormat:@"%zd-%zd-%zd",components.year+(components.month+gapMonthCount)/12,(components.month+gapMonthCount)%12,endDay];
} else {
//依然是當前年份
dateStr = [NSString stringWithFormat:@"%zd-%zd-01",components.year,components.month+gapMonthCount];
newDate = [formatter dateFromString:dateStr];
//新月份的天數
NSInteger newDays = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:newDate].length;
if ([self isEndOfTheMonth:currentDate]) {//當前日期處於月末
endDay = newDays;
} else {
endDay = newDays < components.day?newDays:components.day;
}
dateStr = [NSString stringWithFormat:@"%zd-%zd-%zd",components.year,components.month+gapMonthCount,endDay];
}
newDate = [formatter dateFromString:dateStr];
return newDate;
}
//判斷是否是月末
- (BOOL)isEndOfTheMonth:(NSDate *)date {
NSCalendar *calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
NSInteger daysInMonth = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date].length;
NSDateComponents *componets = [calendar components:NSCalendarUnitDay fromDate:date];
if (componets.day >= daysInMonth) {
return YES;
}
return NO;
}
發現個問題,如上方法得到的日期是GMT時間,直接在datePickerView中顯示的話是正常的(當然前提是datePickerView本地化),但是打印出來就是GMT時間,設定timezone也無用。