CodeQL 文档

错误处理日本时代起始日期

ID: cs/mishandling-japanese-era
Kind: problem
Security severity: 
Severity: warning
Precision: medium
Tags:
   - reliability
   - date-time
Query suites:
   - csharp-security-and-quality.qls

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

当时代发生变化时,调用依赖于默认时代的日期和时间实例化方法可能会产生不明确的日期。在下面的示例中,对使用默认时代的 JapaneseCalendar.ToDateTime 方法的调用返回不同的日期,具体取决于新时代是否已在注册表中定义。

建议

从先前存储在日本日历中的日期创建 DateTime 和 DateTimeOffset 结构时,请使用特定的时代

不要以日本格式存储日期

不要使用硬编码的时代起始日期来计算将日期从日本日期格式转换的日期

仅将 JapaneseCalendar 类用于日期格式化

示例

此示例演示了在日本日期转换中使用当前年份假设的风险

using  System;
using System.Globalization;
public class Example
{
   public static void Main()
   {
      var cal = new JapaneseCalendar();
      // constructing date using current era 
      var dat = cal.ToDateTime(2, 1, 2, 0, 0, 0, 0);
      Console.WriteLine($"{dat:s}");
      // constructing date using current era 
      dat = new DateTime(2, 1, 2, cal);
      Console.WriteLine($"{dat:s}");
   }
}
// Output with the Heisei era current:
//      1990-01-02T00:00:00
//      1990-01-02T00:00:00
// Output with the new era current:
//      2020-01-02T00:00:00
//      2020-01-02T00:00:00

参考

  • ©GitHub 公司
  • 条款
  • 隐私