5

如何从NSDateObjective-C中获取当前年份以及如何确定该年份是否是闰年?

4

4 回答 4

16

您可以执行以下操作:

- (BOOL)isYearLeapYear:(NSDate *) aDate {
    NSInteger year = [self yearFromDate:aDate];
    return (( year%100 != 0) && (year%4 == 0)) || year%400 == 0;
}

- (NSInteger)yearFromDate:(NSDate *)aDate {
    NSDateFormatter *dateFormatter = [NSDateFormatter new];
    dateFormatter.dateFormat = @"yyyy";
    NSInteger year = [[dateFormatter stringFromDate:aDate] integerValue];
    return year;
}
于 2013-05-29T08:52:00.760 回答
6

维基百科:

if year is divisible by 400 then
   is_leap_year
else if year is divisible by 100 then
   not_leap_year
else if year is divisible by 4 then
   is_leap_year
else
   not_leap_year
于 2013-05-29T08:54:50.010 回答
0
 NSDate *date = [NSDate date];
    NSLog(@"dat eis %@",date);

    NSDateFormatter *dateF = [[NSDateFormatter alloc]init];
    [dateF setDateFormat:@"YYYY"];
    NSString *dateS = [dateF stringFromDate:date ];
    NSLog(@"date is %@",dateS);

    int myInt = [dateS intValue];

    if(myInt%4== 0)

    {
        NSLog(@"Its a leap year ");
    }
    else{
        NSLog(@"Not A leap year");
    }
于 2013-05-30T05:04:50.577 回答
0

首先,您需要使用 NSDateComponant 查找年份,如果您将年份除以 4,则为闰年。

于 2013-05-29T08:51:29.790 回答