获取某天、某月的开始时间或结束时间

时间:2022-01-05 17:09:08

// 获取某天、某月的开始时间或结束时间

- (NSString *)getBeginAndEndWith:(NSDate *)newDate unit:(NSCalendarUnit)unit first:(NSInteger)first{
// first 0 表示开始日期 1表示结束日期
if (newDate == nil) {
newDate = [NSDate date];
}
double interval = 0;
NSDate *beginDate = nil;
NSDate *endDate = nil;

NSCalendar *calendar = [NSCalendar currentCalendar];
BOOL ok = [calendar rangeOfUnit:unit startDate:&beginDate interval:&interval forDate:newDate];
//分别修改为 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit
if (ok) {
endDate = [beginDate dateByAddingTimeInterval:interval-1];
}else {
return [NSString stringWithFormat:@"%.0f",[newDate timeIntervalSince1970]];
}
NSTimeInterval beginTimne = [beginDate timeIntervalSince1970];
NSTimeInterval endTimne = [endDate timeIntervalSince1970];

if (first == 0) {
return [NSString stringWithFormat:@"%.0f",beginTimne];
}
return [NSString stringWithFormat:@"%.0f",endTimne];
}

示例:(返回值为时间戳字符串)

1、获取这个月的开始时间

[self getBeginAndEndWith:[NSDate date] unit:NSCalendarUnitMonth first:0];


2、获取这个月的结束时间

self getBeginAndEndWith:[NSDate date] unit:NSCalendarUnitMonth first:1];


3、获取这个星期的开始时间

[self getBeginAndEndWith:[NSDate date] unit:NSCalendarUnitWeekOfYear first:0];


4、获取这个星期的结束时间

[self getBeginAndEndWith:[NSDate date] unit:NSCalendarUnitWeekOfYear first:1];