iOS获取某个日期后n个月的日期
一、给一个时间,给一个数,正数是以后n个月,负数是前n个月;
-(NSDate *)getPriousorLaterDateFromDate:(NSDate *)date withMonth:(NSInteger)month
{
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setMonth:month];
NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *mDate = [calender dateByAddingComponents:comps toDate:date options:0];
return mDate;
}
二、设置你需要增加或减少的年、月、日即可获得新的日期,上述的表示获取mydate日期前一个月的日期,如果该成+1,则是一个月以后的日期,以此类推都可以计算。
- (NSDate *)getLaterDateFromDate:(NSDate *)date withYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps = nil;
comps = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date];
NSDateComponents *adcomps = [[NSDateComponents alloc] init];
[adcomps setYear:year];
[adcomps setMonth:month];
[adcomps setDay:day];
NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:date options:0];
return newdate;
}
补充 : 将时间戳转换为 NSDate
NSDate *date = [self getLaterDateFromDate:[NSDate dateWithTimeIntervalSince1970:[now_time integerValue] withYear:3 month:0 day:0];
补充 :将NSDate转换为 字符串日期格式
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSString *dateStr = [formatter stringFromDate:date];
推荐文章 : https://blog.csdn.net/sqc3375177/article/details/53608867
网友评论