如何使用.NET获得当前季节?(夏天,冬天等......)

Joh*_*zen 5 c# datetime

有没有办法在给定日期的情况下找回一年中的季节?对于地球上的任何地方?

这是基于时区还是半球?

请注意,在南半球,夏季仍处于温暖的月份.

编辑:

为了澄清,我说的是天文季节.

rio*_*fly 11

你可以使用这个简单的代码:

private int getSeason(DateTime date) {
    float value = (float)date.Month + date.Day / 100;   // <month>.<day(2 digit)>
    if (value < 3.21 || value >= 12.22) return 3;   // Winter
    if (value < 6.21) return 0; // Spring
    if (value < 9.23) return 1; // Summer
    return 2;   // Autumn
}
Run Code Online (Sandbox Code Playgroud)

为了包括南半球的季节,代码可以变成:

private int getSeason(DateTime date, bool ofSouthernHemisphere) {
    int hemisphereConst = (ofSouthernHemisphere ? 2 : 0);
    Func<int, int> getReturn = (northern) => {
        return (northern + hemisphereConst) % 4;
    };
    float value = (float)date.Month + date.Day / 100f;  // <month>.<day(2 digit)>
    if (value < 3.21 || value >= 12.22) return getReturn(3);    // 3: Winter
    if (value < 6.21) return getReturn(0);  // 0: Spring
    if (value < 9.23) return getReturn(1);  // 1: Summer
    return getReturn(2);    // 2: Autumn
}
Run Code Online (Sandbox Code Playgroud)

  • 这也无法解释夏至,秋分和冬至并不总是具有相同的日期.你只能通过偶然机会在冬季`if statement`中考虑到这一点.每个闰年,夏至提前一天开始(6.20,而不是6.21),所以你的计算将在2016年关闭.此外,每逢闰年和随后的一年,昼夜平分点开始提前一天(9.22,而不是9.23).最后,冬至每年12.21开始,除了闰年前一年 - 它从12.22开始. (3认同)

Ðаn*_*Ðаn 5

答案取决于您想如何定义每个季节。维基百科上的这张图表显示了每年的确切日期和时间略有变化。

一个可能“足够好”的简单解决方案是使用四个固定日期,例如:3 月 20 日、6 月 21 日、9 月 22 日和 12 月 21 日。


Fox*_*ire 2

我不认为这是标准化的。这也不是众所周知的全球化数据集的一部分。