Comment puis-je obtenir le dernier jour du mois en cours comme un NSDate
?
Réponses
Trop de publicités?
Jonas Schnelli
Points
6084
NSDate *curDate = [NSDate date];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* comps = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:curDate]; // Get necessary date components
// set last of month
[comps setMonth:[comps month]+1];
[comps setDay:0];
NSDate *tDateMonth = [calendar dateFromComponents:comps];
NSLog(@"%@", tDateMonth);
il devrait également travailler.
StCredZero
Points
231
// Adapted from running code in my app
NSDate *curDate = [NSDate date];
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSRange daysRange =
[currentCalendar
rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:curDate];
// daysRange.length will contain the number of the last day
// of the month containing curDate
NSLog(@"%i", daysRange.length);
robdashnash
Points
303
Mettez dans une catégorie
-(NSDate*)lastDayOfMonth
{
NSInteger dayCount = [self numberOfDaysInMonthCount];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
NSDateComponents *comp = [calendar components:
NSYearCalendarUnit |
NSMonthCalendarUnit |
NSDayCalendarUnit fromDate:self];
[comp setDay:dayCount];
return [calendar dateFromComponents:comp];
}
-(NSInteger)numberOfDaysInMonthCount
{
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:TIMEZONE]];
NSRange dayRange = [calendar rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:self];
return dayRange.length;
}
pradox
Points
124
Solution De Contournement De La Fonction:
-(int)GetLastDayOfMonth:(NSDate *)date
{
int last_day = 27;
NSCalendar *cal=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *compsMonth = [cal components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:date];
[compsMonth setDay:last_day];
int month = [compsMonth month];
while(TRUE){
[compsMonth setDay:last_day+1];
NSDate *dateFuture = [cal dateFromComponents:compsMonth];
NSDateComponents *futureComps = [cal components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:dateFuture];
if(month != [futureComps month]){
return last_day;
}
last_day+=1;
}
return last_day;
}