Parse arabic date in c#

后端 未结 1 1081
无人共我
无人共我 2021-01-27 08:28

In an application that I\'m writing I want to parse a specific date which is in the arabic language in c#. For example the date could look like this: ٣٠.١٢.١٩٨٩

But i w

相关标签:
1条回答
  • 2021-01-27 09:11

    Eastern Arabic numerals does not supported by DateTime parsing methods, they only accepts Arabic numerals.

    On the other hand, char.GetNumericValue method is quite good to get a floating-point representation of a numeric Unicode character as a double which perfectly successful for Eastern Arabic numerals as well.

    If your string is always dd.MM.yyyy format based on those numerals, you can split your string with . and get their numeric values from those character, parse to integer those parts, use them in a DateTime(year, month, day) constructor and get it's string representation with dd.MM.yyyy format with a culture that using Gregorian Calendar as a Calendar property like InvariantCulture.

    var s = "٣٠.١٢.١٩٨٩";
    var day =   Int32.Parse(string.Join("",
                            s.Split('.')[0].Select(c => char.GetNumericValue(c)))); // 30
    var month = Int32.Parse(string.Join("",
                            s.Split('.')[1].Select(c => char.GetNumericValue(c)))); // 12
    var year =  Int32.Parse(string.Join("",
                            s.Split('.')[2].Select(c => char.GetNumericValue(c)))); // 1989
    
    var dt = new DateTime(year, month, day);
    Console.WriteLine(dt.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture)); // 30.12.1989
    

    Here a demonstration.

    As an alternative, you can create your own Dictionary<char, char> structure and you can replace Eastern Arabic characters mapped with Western Arabic characters.

    var mapEasternToWestern = new Dictionary<char, char>
    { 
        {'٠', '0'}, 
        {'١', '1'}, 
        {'٢', '2'}, 
        {'٣', '3'}, 
        {'٤', '4'}, 
        {'٥', '5'}, 
        {'٦', '6'}, 
        {'٧', '7'}, 
        {'٨', '8'}, 
        {'٩', '9'}
    };
    
    0 讨论(0)
提交回复
热议问题