Search code examples
c#datetimeubuntucentosinvariantculture

C# DateTime.ToString return different result in Ubuntu and Centos


I have the following code:

public static void Main(string[] args)
{
     var dateTime = DateTimeHelper
        .ConvertPersianDateTime("12/22/1402", "09:33:12")
        .ToString("D");

     Console.WriteLine(dateTime);
}
public static DateTime ConvertPersianDateTime(string persianDate, string persianTime)
{
    var isParse = DateTime.TryParse($"{persianDate} {persianTime}",
                                new CultureInfo("fa-IR"),
                                DateTimeStyles.None, out var result);

    return isParse ? result : DateTime.Now;
}

When I run the program in ubuntu server, I get this result:

Tuesday, March 12, 2024

But when I run the program in centos server, I get this result:

Wednesday, December 22, 1402

Why result of centos server is different with ubuntu?


Solution

  • I think this is related with this Github issue.

    I quickly looked at Centos OS and I found the ICU there not setting the PersianCalendar as the default calendar to the fa-IR. So by default it uses the GregorianCalendar as the default calendar there. You can work around this easily by manually setting the PersianCalendar as the default calendar in the created culture object.

    Also from this supported distributions page;

    The following table is a list of currently supported .NET releases on CentOS Linux 7. These versions remain supported until either the version of .NET reaches end-of-support or the version of CentOS Linux is no longer supported.

    CentOS Linux 7 --> .NET 7, 6

    CentOS Linux 8 reached an early End Of Life (EOL) on December 31st, 2021. For more information, see the official CentOS Linux EOL page. Because of this, .NET isn't supported on CentOS Linux 8.

    So, this looks like a ICU problem rather than a .NET problem. You can always file an issue for that but remember Centos 8 is not supporting OS any more for .NET development.


    Update:

    By adding PersianCalendar to CultureInfo problem will fix:

    public static DateTime ConvertPersianDateTime(string persianDate, string persianTime)
    {
        var faCulture = new CultureInfo("fa-IR");
    
        faCulture.DateTimeFormat.Calendar = new PersianCalendar(); // This what will make it work.
    
        var isParse = DateTime.TryParse($"{persianDate} {persianTime}",
                                    faCulture,
                                    DateTimeStyles.None, out var result);
    
        return isParse ? result : DateTime.Now;
    }