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);
该代码显示“12 2147483647 2147483647”
如何获得月份和年份(整数)
如何添加/转发一天? (如果我们也是这个月的第一个!)
请你注意: - )
答案 0 :(得分:9)
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];
希望这会有所帮助
答案 1 :(得分:2)
向NSDayCalendarUnit | NSWeekdayCalendarUnit
添加更多单位 - 您没有请求月份或年份,因此它们无效!
添加/减去配置为1天NSDateComponents
的{{1}}对象。或者,也可能正确,使用[NSCalendar dateByAddingComponents:toDate:options:]