2

我正在研究 C# DateTime 结构的 C++ 半端口。(如果你想看看它是公共领域。)我真的很喜欢让这个类围绕一个单独的私有 64 位整数。它使许多操作变得超级简单,并使类保持轻量级。我正在努力的部分是从刻度到年、月或日的计算。目前,我使用循环来获得正确的答案:我一次减去一年的刻度,这样我就可以在正确的时间减去闰年的刻度。

好消息是它得到了正确的答案。如果可能的话,我只是更喜欢使用直接的数学方法。我知道 C# 不是开源的,但是有没有办法查看 DateTime 的实现?如果不是,我在哪里可以找到将 N 天转换为年、月和日的数学公式?

请不要对过早的优化发表评论。我没有截止日期。我只是想让这变得更好。这是一次学习经历。

更新 - 对于任何好奇的人,我也确实设法看到了 Mono 中的实现。源代码中有一个纯文本 DateTime.cs。

4

4 回答 4

2

Date以下是我之前实现的结构的摘录。构造函数包含用于将自 0001 年 1 月 1 日以来的天数(“序列号”)转换为年、月和日的主要逻辑。它基于 的实际源代码System.DateTime,但我使用了更具描述性的变量名称并添加了注释。

从多个DateTime刻度转换时,您需要先除以TimeSpan.TicksPerDay得到序列号。

/// <summary>
/// Represents a date between January 1, 0001 CE, and December 31, 9999 CE, in the proleptic Gregorian calendar.
/// </summary>
public struct Date
{
    public const Int32 DaysPerYear = 365;
    public const Int32 MonthsPerYear = 12;

    private const UInt32 MaxSerialNumber = 3652058;
    private const UInt32 December = 11; // 0-based
    private const UInt32 DaysInDecember = 31;

    private const UInt32 LeapYearInterval1 = 4;
    private const UInt32 LeapYearInterval2 = 100;
    private const UInt32 LeapYearInterval3 = 400;

    private const UInt32 DaysPerLeapYearInterval1 =
        DaysPerYear * LeapYearInterval1 + 1; // +1 leap day every 4 years
    private const UInt32 DaysPerLeapYearInterval2 =
        DaysPerLeapYearInterval1 * (LeapYearInterval2 / LeapYearInterval1) - 1; // -1 leap day every 100 years
    private const UInt32 DaysPerLeapYearInterval3 =
        DaysPerLeapYearInterval2 * (LeapYearInterval3 / LeapYearInterval2) + 1; // +1 leap day every 400 years

    private static readonly UInt32[] DaysOfYear =
        new UInt32[(MonthsPerYear + 1) * 2]
        {
            0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365,
            0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366,
        };

    private readonly UInt16 _zeroBasedYear; // 0 to 9998
    private readonly Byte _zeroBasedMonth; // 0 to 11
    private readonly Byte _zeroBasedDay; // 0 to 30

    /// <summary>
    /// Initializes a new instance of the <see cref="Date" /> structure to a specified serial number.
    /// </summary>
    /// <param name="serialNumber">
    /// The <see cref="SerialNumber" /> of the new <see cref="Date" />.
    /// </param>
    /// <exception cref="ArgumentOutOfRangeException">
    /// <paramref name="serialNumber" /> is less than 0 or greater than 3652058.
    /// </exception>
    public Date(Int32 serialNumber)
    {
        Require.IsBetween("serialNumber", serialNumber, 0, (Int32)MaxSerialNumber);
        UInt32 days = (UInt32)serialNumber;

        // Find the first year of the 400-year period that contains the date:
        UInt32 zeroBasedYear = days / DaysPerLeapYearInterval3 * LeapYearInterval3;
        days %= DaysPerLeapYearInterval3;

        // Within the 400-year period, advance to the first year of the century that contains the date:
        UInt32 centuries = days / DaysPerLeapYearInterval2;
        zeroBasedYear += centuries * LeapYearInterval2;

        // Special case: If the date is the last day (December 31) of the 400-year period,
        // then "centuries" will be out of range because the fourth century has one more day than the others:
        if (centuries == LeapYearInterval3 / LeapYearInterval2)
            goto December31;

        days %= DaysPerLeapYearInterval2;

        // Within the century, advance to the first year of the 4-year period that contains the date:
        zeroBasedYear += days / DaysPerLeapYearInterval1 * LeapYearInterval1;
        days %= DaysPerLeapYearInterval1;

        // Within the 4-year period, advance to the year that contains the date:
        UInt32 years = days / DaysPerYear;
        zeroBasedYear += years;

        // Special case: If the date is the last day (December 31) of the 4-year period,
        // then "years" will be out of range because the fourth year has one more day than the others:
        if (years == LeapYearInterval1)
            goto December31;

        days %= DaysPerYear;

        // Estimate the month using an efficient divisor:
        Int32 index = GetDaysOfYearIndex(zeroBasedYear);
        UInt32 zeroBasedMonth = days / 32;

        // If the estimate was too low, adjust it:
        if (days >= DaysOfYear[index + (Int32)zeroBasedMonth + 1])
            ++zeroBasedMonth;

        _zeroBasedYear = (UInt16)zeroBasedYear;
        _zeroBasedMonth = (Byte)zeroBasedMonth;
        _zeroBasedDay = (Byte)(days - DaysOfYear[index + (Int32)zeroBasedMonth]);
        return;

    December31:
        _zeroBasedYear = (UInt16)(zeroBasedYear - 1);
        _zeroBasedMonth = (Byte)December;
        _zeroBasedDay = (Byte)(DaysInDecember - 1);
    }

    private static Int32 GetDaysOfYearIndex(UInt32 zeroBasedYear)
    {
        return !InternalIsLeapYear(zeroBasedYear) ? 0 : MonthsPerYear + 1;
    }

    private static Boolean InternalIsLeapYear(UInt32 zeroBasedYear)
    {
        UInt32 year = zeroBasedYear + 1;
        return
            (year % LeapYearInterval1 == 0) &&
            (year % LeapYearInterval2 != 0 || year % LeapYearInterval3 == 0);
    }
}
于 2012-06-24T17:15:23.110 回答
1

您无法轻松获得 .NET 实现(无需反编译),但欢迎您查看Noda Time的源代码——我基于Joda Time的 .NET 日期和时间项目。这显然必须做类似的事情。

就我个人而言,我不会DateTime其用作日期和时间 API 的起点。它有各种不幸的方面。有更好的日期/时间 API 可供查看(当然不仅仅是 Noda Time)。

于 2012-06-24T16:55:31.270 回答
0

尝试使用反射器查看实现?尽管它最终可能会调用一些非托管代码。或者看看 Mono 看看他们是否有实现。

于 2012-06-24T16:55:02.487 回答
0

对于后来发现这个问题的任何人,我找到DateTime.

http://referencesource.microsoft.com/#mscorlib/system/datetime.cs

于 2014-04-14T21:00:19.940 回答