CodeQL 文档

“DateTime” 构造函数的年份参数不安全

ID: cs/unsafe-year-construction
Kind: path-problem
Security severity: 
Severity: warning
Precision: medium
Tags:
   - date-time
   - reliability
Query suites:
   - csharp-security-and-quality.qls

点击查看 CodeQL 代码库中的查询

当通过对不同的 DateTime 对象执行算术运算,在构造函数中设置年、月和日来创建 System.DateTime 对象时,存在设置的日期无效的风险。

在闰年,此类代码可能会引发 ArgumentOutOfRangeException,并显示消息“年、月和日参数描述了一个不可表示的 DateTime。”

建议

要根据不同的 System.DateTime 对象创建 System.DateTime 对象,请使用适当的方法来操作日期,而不是进行算术运算。

示例

在此示例中,我们在创建新的 System.DateTime 对象时,将当前日期增加/减少一年。这在大多数情况下都可以正常工作,但在任何给定的 2 月 29 日,结果值都将无效。

using System;
public class UnsafeYearConstructionBad
{
    public UnsafeYearConstructionBad()
    {
        DateTime Start;
        DateTime End;
        var now = DateTime.UtcNow;
        // the base-date +/- n years may not be a valid date.
        Start = new DateTime(now.Year - 1, now.Month, now.Day, 0, 0, 0, DateTimeKind.Utc);
        End = new DateTime(now.Year + 1, now.Month, now.Day, 0, 0, 1, DateTimeKind.Utc);
    }
}

为了修复此错误,我们通过在其上调用 AddYears 方法来为当前日期增加/减少年份。

using System;
public class UnsafeYearConstructionGood
{
    public UnsafeYearConstructionGood()
    {
        DateTime Start;
        DateTime End;
        var now = DateTime.UtcNow;
        Start = now.AddYears(-1).Date;
        End = now.AddYears(-1).Date.AddSeconds(1);
    }
}

参考

  • ©GitHub, Inc.
  • 条款
  • 隐私