iOS Objective-C: 获取指定年月的最后一天日期
您可以使用 NSCalendar 和 NSDateComponents 来实现这个功能。以下是一个示例代码:
- (NSInteger)getSelectedDayForYear:(NSInteger)year month:(NSInteger)month {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *currentComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
NSDateComponents *selectedComponents = [[NSDateComponents alloc] init];
selectedComponents.year = year;
selectedComponents.month = month;
selectedComponents.day = 1;
NSDate *selectedDate = [calendar dateFromComponents:selectedComponents];
if ([selectedDate compare:[NSDate date]] == NSOrderedDescending) {
// 选中日期在当前日期之后
return currentComponents.day;
} else {
NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:selectedDate];
return range.length;
}
}
使用示例:
NSInteger selectedDay = [self getSelectedDayForYear:2023 month:7];
NSLog('Selected day: %ld', (long)selectedDay);
上面的代码将根据传入的年和月返回选中的日期。如果选中日期在当前日期之后,将返回当前日期的天数。否则,将返回选中日期对应月份的天数。
原文地址: https://www.cveoy.top/t/topic/p4OG 著作权归作者所有。请勿转载和采集!