NSDate *today = [NSDate date]; NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:today]; NSInteger year = [components year]; NSInteger month = [components month]; // 设置日期格式化对象 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"MMMM yyyy"]; // 获取当前月份第一天的日期 NSDateComponents *firstDayComponents = [[NSDateComponents alloc] init];报红
时间: 2023-11-26 19:03:20 浏览: 164
看起来你没有给 `firstDayComponents` 对象设置时间和日期。你需要为 `firstDayComponents` 对象设置年份和月份,然后使用`NSCalendar`的 `dateFromComponents:` 方法将其转换为 `NSDate` 对象。以下是一个示例代码:
```
// 设置日期格式化对象
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMMM yyyy"];
// 获取当前月份第一天的日期
NSDate *today = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:today];
NSInteger year = [components year];
NSInteger month = [components month];
// 设置 firstDayComponents 对象
NSDateComponents *firstDayComponents = [[NSDateComponents alloc] init];
[firstDayComponents setYear:year];
[firstDayComponents setMonth:month];
[firstDayComponents setDay:1];
// 将 firstDayComponents 转换为 NSDate 对象
NSDate *firstDateOfMonth = [calendar dateFromComponents:firstDayComponents];
```
这样,`firstDateOfMonth` 对象就是当前月份的第一天的日期。
阅读全文