//获取 当前月的下一月,上一月
- (void)setupRequestMonth
{
NSDate *currentDate = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM"];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
// [lastMonthComps setYear:1]; // year = 1表示1年后的时间 year = -1为1年前的日期,month day 类推
[lastMonthComps setMonth:-1];
NSDate *newdate = [calendar dateByAddingComponents:lastMonthComps toDate:currentDate options:0];
NSString *dateStr = [formatter stringFromDate:newdate];
NSLog(@"date str = %@", dateStr);
}
//通过指定日期获取 当月 月初和月末的两天
- (NSArray *)getMonthFirstAndLastDayWith:(NSString *)dateStr{
NSDateFormatter *format=[[NSDateFormatter alloc] init];
[format setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
NSDate *newDate=[format dateFromString:dateStr];
double interval = 0;
NSDate *firstDate = nil;
NSDate *lastDate = nil;
NSCalendar *calendar = [NSCalendar currentCalendar];
BOOL OK = [calendar rangeOfUnit:NSCalendarUnitMonth startDate:& firstDate interval:&interval forDate:newDate];
if (OK) {
lastDate = [firstDate dateByAddingTimeInterval:interval - 1];
}else {
return @[@"",@""];
}
NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
[myDateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
NSString *firstString = [myDateFormatter stringFromDate: firstDate];
NSString *lastString = [myDateFormatter stringFromDate: lastDate];
NSLog(@"first%@----PPPP",firstString);
NSLog(@"last%@-----OOOOO",lastString);
return @[firstString, lastString];
}
//测试 相减一天的处理
- (BOOL)isSameNoDay:(NSDate*)date1 date2:(NSDate*)date2
{
NSCalendar* calendar = [NSCalendar currentCalendar];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];
return [comp1 day]+1 == [comp2 day] &&
[comp1 month] == [comp2 month] &&
[comp1 year] == [comp2 year];
}
//获取日期的字符串
-(NSString*)getDataStr{
NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
return [formatter stringFromDate:date];
}
//获取指定日期的字符串
-(NSString*)getDataStrByDate:(NSDate*)date{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
return [formatter stringFromDate:date];
}
//获取当前日期
-(NSDate*)getData{
NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
return date;
}