NSDate, NSCalendar, and NSDateComponents

NSDate *today = [NSDate date]; NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; [calendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+2"]]; NSDateComponents *dateComponents = [calendar components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today]; NSInteger day = [dateComponents day]; NSInteger month = [dateComponents month]; NSInteger year = [dateComponents year]; NSLog(@" %i %i %i ", day, month, year); 

This code shows me "12 2147483647 2147483647"

How can I get the month and year (integer)

How to add / forward one day? (if we are also the first month)!

Introduce yourself for your attention :-)

+4
source share
2 answers
 NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit; NSDate *date = [NSDate date]; NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date]; NSInteger year = [dateComponents year]; NSInteger month = [dateComponents month]; NSInteger day = [dateComponents day]; NSInteger hour = [dateComponents hour]; NSInteger minute = [dateComponents minute]; NSInteger second = [dateComponents second]; [calendar release]; 

hope this helps

+9
source
  • Add units to NSDayCalendarUnit | NSWeekdayCalendarUnit NSDayCalendarUnit | NSWeekdayCalendarUnit - You are not requesting a month or year, so they are not valid!

  • Add / subtract the NSDateComponents object configured for 1 day, and [NSCalendar dateByAddingComponents:toDate:options:] . Alternatively, and possibly in exactly the same way, use [NSDate dateWithTimeInterval:sinceDate:]

+2
source

Source: https://habr.com/ru/post/1347702/


All Articles