PersianCalendar无法将年/月/ 31(日)转换为标准日期

Ehs*_*bar 6 c# datetime persian datetime-format datetime-conversion

我想转换persianDatestandarddate.

public DateTime ConvertPersianToEnglish(string persianDate)
{
    string[] formats = { "yyyy/MM/dd", "yyyy/M/d", "yyyy/MM/d", "yyyy/M/dd" };
    DateTime d1 = DateTime.ParseExact(persianDate, formats,
                                      CultureInfo.CurrentCulture, DateTimeStyles.None);
    PersianCalendar persian_date = new PersianCalendar();
    DateTime dt = persian_date.ToDateTime(d1.Year, d1.Month, d1.Day, 0, 0, 0, 0, 0);
    return dt;
}
Run Code Online (Sandbox Code Playgroud)

Persiandate具有格式是这样的:1392/10/12(Year/month/day)

在我的应用程序中,我试图转换Year/month/31为标准时间,但我收到此错误:

{System.FormatException: String was not recognized as a valid DateTime.
   at System.DateTimeParse.ParseExactMultiple(String s, String[] formats, DateTimeFormatInfo dtfi, DateTimeStyles style)
Run Code Online (Sandbox Code Playgroud)

我得到错误的确切值是 1393/04/31

Jon*_*eet 6

谢尔盖明确使用使用波斯日历的文化的解决方案应该有效,但另一种选择是使用我的Noda Time库:

using System;
using System.Globalization;
using NodaTime;
using NodaTime.Text;

public class Test
{
    public static void Main()        
    {
        // Providing the sample date to the pattern tells it which
        // calendar to use.

        // Noda Time 2.0 uses a property instead of a method.
        // var calendar = CalendarSystem.Persian;           // 2.0+
        var calendar = CalendarSystem.GetPersianCalendar(); // 1.x

        LocalDate sampleDate = new LocalDate(1392, 10, 12, calendar);
        var pattern = LocalDatePattern.Create(
            "yyyy/M/d", CultureInfo.InvariantCulture, sampleDate);
        string text = "1393/04/31";
        ParseResult<LocalDate> parseResult = pattern.Parse(text);
        if (parseResult.Success)
        {
            LocalDate date = parseResult.Value;
            // Use the date
        }
    }    
}
Run Code Online (Sandbox Code Playgroud)

不同的是DateTime,LocalDate这里的结果知道它只是一个日期(因此不会提供时间方面)并且还知道它所处的日历系统(因此您不需要继续调用方法calendar.GetYear(date)来获取特定部分).

请注意,解析模式yyyy/M/d将能够使用前导零解析值,因此您不需要多个模式.如果你知道格式总是有两位数的月份和日期,不过,我会明确地使用yyyy/MM/dd来代替.