如何在iphone中找出当年的闰年

时间:2013-05-29 08:44:22

标签: iphone ios objective-c xcode ipad

如何从NSDate获取当前年份以及如何在Objective-C中查明该年是否为闰年?

4 个答案:

答案 0 :(得分:15)

您可以执行以下操作:

- (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;
}

答案 1 :(得分:4)

百科:

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

答案 2 :(得分:0)

首先你需要使用NSDateComponant找到年份,如果你得到年份除以4,如果除以那么这是闰年。

答案 3 :(得分: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");
    }