Search code examples
c#datetimeculturetryparsearabic-support

Arabic culture datetime parsing not returning expected values


I'm not sure if the problem i'm having is because of a lack of understanding of how the datetime's work in the Umm al-Qura calendar works, or if it's a bug.

Basically i'm working on writing a test to ensure that an internal utility class properly parses values regardless of the current culture.

In the code below, the goal is to have dt1 equal to dt2.

    public void ArabicTesting()
    {
        CultureInfo culture = new CultureInfo("ar");

        // Initialize a new datetime (04/01/2048 06:21:01 AM)
        DateTime dt1 = new DateTime(2048, 4, 1, 6, 21, 1);

        // Convert the datetime to a string using arabic cultureinfo
        // string ends up being "17/06/70 06:21:01 ص,"
        string dt2_string = $"{dt1.ToString(culture.DateTimeFormat.ShortDatePattern)} {dt1.ToString(culture.DateTimeFormat.LongTimePattern)}";

        // Parse the string
        DateTime dt2;
        DateTime.TryParse(dt2_string, culture, DateTimeStyles.None, out dt2);
    }

The problem is that DateTime.TryParse is parsing the datetime as a string into a datetime that appears the same, but has different values than what is expected.

Here are a couple of screenshots of what is happening:

dt1 dt2

If you look at both dt1 and dt2 preview values, they appear the same "17/06/70 06:21:01 ص,", however, the actual values of the objects are completely different.

Does anybody know if this is an MS bug, or is it because I am not passing the correct string value into the DateTime.TryParse method?


Solution

  • To make sure the full date is captured try using LongDatePattern instead of ShortDatePattern.

    string dt2_string = $"{dt1.ToString(culture.DateTimeFormat.LongDatePattern)} {dt1.ToString(culture.DateTimeFormat.LongTimePattern)}";
    

    The results of the 2 could be different based on this as the ShortDatePattern could omit a datepart that might then have a default value be wrongly assumed in the parse method such as the full year (example). What part is or is not assumed depends on the culture used and some cultures probably work either way while others will have problems (like Arabic).

    To better debug why this happened in this particular case you could compare the 2 strings from dt1.ToString(culture.DateTimeFormat.LongDatePattern) and dt1.ToString(culture.DateTimeFormat.ShortDatePattern) and see what part of the date could be substituted with a default value from the current date/time at run time.