.NET How to parse a Persian / Farsi date string (Jalali calendar) into a DateTime object?

前端 未结 4 1859
醉梦人生
醉梦人生 2020-12-28 09:14

I\'ve run across several great code libraries for converting a Persian (Jalali calendar) date to a Gregorian date. However, my original source is a string, not a DateTime ob

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-28 09:18

    For parsing the date string, I simply use the default calendar to get the date values (year, month, day, etc.)

    I then use this library here to convert the Persian date values to the Gregorian date values.

    My code now looks like this:

    string persianDate = "1390/02/07";
    CultureInfo persianCulture = new CultureInfo("fa-IR");
    DateTime persianDateTime = DateTime.ParseExact(persianDate, "yyyy/MM/dd", persianCulture);    // this parses the date as if it were Gregorian
    
    JalaliCalendar jc = new JalaliCalendar();
    // convert the Persian calendar date to Gregorian
    DateTime gregorianDateTime = jc.ToDateTime(persianDateTime.Year, persianDateTime.Month, persianDateTime.Day, persianDateTime.Hour, persianDateTime.Minute, persianDateTime.Second, persianDateTime.Millisecond);
    

    Of course, I'll have to take care of date components with names (months, days of the week) myself, but I can deal with that pretty easily.

提交回复
热议问题