How to convert a Persian date into a Gregorian date?

前端 未结 9 1286
萌比男神i
萌比男神i 2020-12-30 04:30

I use the function below to convert Gregorian dates to Persian dates, but I\'ve been unable to write a function to do the reverse conversion. I want a function that converts

9条回答
  •  猫巷女王i
    2020-12-30 05:09

    DateTime is always in the Gregorian calendar, effectively. Even if you create an instance specifying a dfferent calendar, the values returned by the Day, Month, Year etc properties are in the Gregorian calendar.

    As an example, take the start of the Islamic calendar:

    using System;
    using System.Globalization;
    
    class Test
    {
        static void Main()
        {
            DateTime epoch = new DateTime(1, 1, 1, new HijriCalendar());
            Console.WriteLine(epoch.Year);  // 622
            Console.WriteLine(epoch.Month); // 7
            Console.WriteLine(epoch.Day);   // 18
        }
    }
    

    It's not clear how you're creating the input to this method, or whether you should really be converting it to a string format. (Or why you're not using the built-in string formatters.)

    It could be that you can just use:

    public static string FormatDateTimeAsGregorian(DateTime input)
    {
        return input.ToString("yyyy'/'MM'/'dd' 'HH':'mm':'ss",
                              CultureInfo.InvariantCulture);
    }
    

    That will work for any DateTime which has been created appropriately - but we don't know what you've done before this.

    Sample:

    using System;
    using System.Globalization;
    
    class Test
    {
        static void Main()
        {
            DateTime epoch = new DateTime(1, 1, 1, new PersianCalendar());
            // Prints 0622/03/21 00:00:00
            Console.WriteLine(FormatDateTimeAsGregorian(epoch));
        }
    
        public static string FormatDateTimeAsGregorian(DateTime input)
        {
            return input.ToString("yyyy'/'MM'/'dd' 'HH':'mm':'ss",
                                  CultureInfo.InvariantCulture);
        }
    }
    

    Now if you're not specifying the calendar when you create the DateTime, then you're not really creating a Persian date at all.

    If you want dates that keep track of their calendar system, you can use my Noda Time project, which now supports the Persian calendar:

    // In Noda Time 2.0 you'd just use CalendarSystem.Persian
    var persianDate = new LocalDate(1390, 7, 18, CalendarSystem.GetPersianCalendar());
    var gregorianDate = persianDate.WithCalendar(CalendarSystem.Iso);
    

提交回复
热议问题