如何计算在C#至两年的闰年数 [英] How to calculate number of leap years between two years in C#

查看:417
本文介绍了如何计算在C#至两年的闰年数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更好的方式来计算两个年份之间闰年数。假设我有开始日期和结束日期。

Is there a better way to calculate number of leap years between two years. Assuming I have start date and end date.

我有我的代码,但我觉得应该有更优雅的方式。

I have my code, but I think there should be more elegant way.

调用代码:

var numberOfLeapYears = NumberOfLeapYears(startDate.Year + 1, endDate.Year - 1);



函数本身:

function itself:

    private static int NumberOfLeapYears(int startYear, int endYear)
    {
        var counter = 0;

        for (var year = startYear; year <= endYear; year++)
            counter += DateTime.IsLeapYear(year) ? 1 : 0;

        return counter;
    }



所以,如果我的startDate =10/16/2006和结束日期= 2004年4月18日我应该只在1导致闰年(2000年)。换言之的startDate的年份和结束日期的年份不应该被计算出来,只能岁之间。

So if I have startDate = "10/16/2006" and endDate = "4/18/2004" I should only have 1 leap year (2000) in result. Another words startDate's Year and endDate's year should not be calculated, only years in between.

在此先感谢您的帮助。

推荐答案

您可以用分析法指望它。一年是闰年,如果它可以被4整除,但不能被100通过400假设您可以通过下面的代码计算这样的数量进行划分,除非情况时,它可分为:

You can count it using analytic approach. A year is a leap year if it can be divided by 4, but can't be divided by 100, except of case when it can be divided by 400. Assuming that you can count such number by following code:

        static int LeapYearsBetween(int start, int end)
        {
            System.Diagnostics.Debug.Assert(start < end);
            return LeapYearsBefore(end) - LeapYearsBefore(start + 1);
        }

        static int LeapYearsBefore(int year)
        {
            System.Diagnostics.Debug.Assert(year > 0);
            year--;
            return (year / 4) - (year / 100) + (year / 400);
        }



某种数学魔法。它比使用LINQ多少有效的解决方案。

Some kind of math magic. It is much effective solution than using LINQ.

这篇关于如何计算在C#至两年的闰年数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆