c# - 如何使用 .NET 获取当前季节? (夏季、冬季等...)

标签 c# datetime

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

这是基于时区和半球的吗?

请注意,在南半球,那个夏天仍然处于温暖的月份。

编辑:

澄清一下,我说的是天文数字seasons .

最佳答案

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

private int getSeason(DateTime date) {
    float value = (float)date.Month + date.Day / 100f;  // <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
}

要包含南半球的季节,代码可以变成:

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
}

关于c# - 如何使用 .NET 获取当前季节? (夏季、冬季等...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1579587/

相关文章:

python - Seaborn/Matplotlib 日期轴条形图次要-主要刻度格式

c# - 向现有 WebAPI 添加版本控制

c# - 使用相机进行面部检测坐标

c# - 为什么将类移动到 Visual Studio 中的新文件夹中会造成破坏?

php - 获取一周中的天数范围

Python 按日期时间分组

c# - datetime 从哪里获取它的数据从 asp.net/c#

C# 浮点精度

c# - Linq 找到长度最长的点对?

php - 使用 DatePeriod 和 DateInterval 获取一段时间内的某些工作日