【问题标题】:problem with persian calendar in year 14001400年波斯历的问题
【发布时间】:2021-07-21 17:23:42
【问题描述】:

我想使用波斯日历类将 波斯日期 更改为 C# 中的标准 DateTime 格式。 但由于将年份更改为 1400,它抛出异常,如下所示:

ArgumentOutOfRangeException: Specified time is not supported in this calendar. It should be between 22/03/22 12:00:00 AM (Gregorian date) and 99/12/31 11:59:59 PM (Gregorian date), inclusive. (Parameter 'time')
Actual value was 0.

我检查了波斯历类,我发现了这个:

if (year < 1 || year > MaxCalendarYear || month < 1 || month > 12)
{
  throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}

抛出异常。 现在我应该怎么做才能解决这个问题?

【问题讨论】:

    标签: c# asp.net datetime asp.net-core persian-calendar


    【解决方案1】:

    总结

    您将一个空的DateTime(例如new DateTime())传递给强大的PersianCalendar 的方法之一。

    请注意,DateTimestruct(不是 class),任何未初始化/设置的 DateTime 类型的属性或变量都将具有此最小值。

    也许您正在反序列化一个没有此值但类的属性不可为空的 json。也许数据库中的列为空,但模型的属性不可为空等。

    详情

    这个异常是由类中很多方法调用的PersianCalendar的CheckTicksRange方法抛出的:

    internal static void CheckTicksRange(long ticks)
    {
        if (ticks < s_minDate.Ticks || ticks > s_maxDate.Ticks)
        {
            throw new ArgumentOutOfRangeException(
                "time",
                ticks,
                SR.Format(SR.ArgumentOutOfRange_CalendarRange, s_minDate, s_maxDate));
        }
    }
    

    您收到的错误消息以字符串结尾:Actual value was 0.。这意味着传入的 DateTime 有 0 个刻度,这意味着它是空的。

    例如:

    try
    {
        new PersianCalendar().GetYear(time: new DateTime());
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    

    这会导致:

    Specified time is not supported in this calendar. It should be between 22/03/0622 00:00:00 (Gregorian date) and 31/12/9999 23:59:59 (Gregorian date), inclusive. (Parameter 'time')
    Actual value was 0.  
    

    请注意“实际值为 0。”。

    还请注意,对于我的语言环境,例外情况更清楚一些,因为日期包含 4 位数的年份。

    如果我们使用无效的日期,但不是空的,则异常消息的结尾会有所不同:

    new PersianCalendar().GetYear(time: new DateTime(year: 622, month: 1, day: 1));
    

    结果:

    Specified time is not ... 
    ... 'time')
    Actual value was 195968160000000000.
    

    【讨论】:

      【解决方案2】:

      为什么不借助PersianCalendar显式 转换?

      using System.Globalization;
      
      ...
      
      // What does Gregorian date correspond to Persian new year (1400)? 
      int year = 1400;
      int month = 1;
      int day = 1;
      
      DateTime result = new PersianCalendar().ToDateTime(year, month, day, 0, 0, 0, 0);
      
      Console.WriteLine($"{result:dd MMMM yyyy}");
      

      结果:

      21 March 2021
      

      当至少一个参数超出范围时抛出ArgumentOutOfRangeExceptionmonth 应在1..12 等范围内。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-25
        • 2022-08-10
        • 1970-01-01
        • 2020-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多