C# 如何在不使用 Date/DateTime/TimeSpan 的情况下计算两个日期之间的天数?

C# How to calculate days between to dates without using Date/DateTime/TimeSpan?

我有面试任务要做。我需要在不使用 Date/DateTime/TimeSpan classes 的情况下计算到日期之间的日期数。

如何仅使用字符串 class 来做到这一点?

最好的问候 //瓦蒙

你不能不知道日期与哪种文化有关。

您必须首先知道我们在谈论哪种文化,然后您可以使用 DateFormat 对象识别分隔符和日期部分。

然后只需使用 Split 方法传递日期分隔符,这样您就可以检索每个日期部分并执行计算。

但你还必须定义月份持续时间(28 天、30 天、31 天),更不用说闰年了。

要确定leap-years可以实现下面的算法

if (year is not divisible by 4) then (it is a common year)
else if (year is not divisible by 100) then (it is a leap year)
else if (year is not divisible by 400) then (it is a common year)
else (it is a leap year)

对于月持续时间,声明一个包含十二个项目的数组来存储月持续时间,并使用月份编号作为索引来检索每个月的长度。

把你的日期转换成a Julian day number比较正常:

// This is a standard formula for conversion.
// See the Wikipedia page on Julian days for more information.

public static long ToJulian(int year, int month, int day)
{
    if (month < 3)
    {
        month = month + 12;
        year = year - 1;
    }

    return  day + (153 * month - 457) / 5 + 365 * year + (year / 4) - (year / 100) + (year / 400) + 1721119;
}

要调用它,您需要先将日期字符串解析为月、日和年:

    public static long ToJulian(string mdy)
    {
        var split = mdy.Split('/');
        return ToJulian(int.Parse(split[2]), int.Parse(split[0]), int.Parse(split[1]));
    }

然后你可以将这两个日期转换成Julian格式并相减以求出天数的差异。

这是一个示例,它表明与使用 DateTime 和 TimeSpan 相比,Julian 的结果是相同的:

    static void Main()
    {
        string date1 = "5/31/1961";
        string date2 = "1/5/2017";

        long diff1 = ToJulian(date2) - ToJulian(date1);

        Console.WriteLine("diff1 = " + diff1);

        long diff2 = (long)(
            DateTime.Parse(date2, CultureInfo.InvariantCulture) - 
            DateTime.Parse(date1, CultureInfo.InvariantCulture))
            .TotalDays;

        Console.WriteLine("diff2 = " + diff2);
    }