我正在使用Calender应用程序,当我导航到下个月时,它工作正常,因为我能够获得该月的最后一天,并且从那里我可以获得下个月的第一天。但是当我导航到上个月我无法获得上个月的第一天。有没有办法获得上个月的第一天。
答案 0 :(得分:7)
以下对我来说没问题
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *currentDate = [NSDate date];
NSDateComponents *components = [calendar components:(NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:currentDate];
components.month = components.month - 1;
components.day = 1;
NSDate *newDate = [calendar dateFromComponents:components];
如果您当前的月份是1月,这也有效。 NSDateComponents将自动减少年份并将月份设置为12月。
答案 1 :(得分:1)
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear
fromDate:[NSDate date]];
components.day = 1;
components.month = components.month - 1;
NSDate *lastmonthDay1 = [[NSCalendar currentCalendar] dateFromComponents: components];
NSLog(@"First day of last month====: %@", [lastmonthDay1 descriptionWithLocale:[NSLocale currentLocale]]);
答案 2 :(得分:0)
您可以执行以下操作....
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDateComponents *comp = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]];
[comp setDay:1];
[comp setMonth:CurrentMonth];//previous month
[comp setYear:currentYear];
NSDate *firstDayOfMonthDate = [gregorian dateFromComponents:comp];
NSCalendar *cal1=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps1 = [cal1 components:NSWeekdayCalendarUnit fromDate:firstDayOfMonthDate];
// 1 for mon 8 for sun
int startWithDay=[comps1 weekday]==1?8:[comps1 weekday];
//1 for monday
// 2 for tuesday and so on....
让我知道它的工作与否!!!
快乐编码!!!!