1

I'm getting UTC time from devices that appear in arabic unicode. How can I convert this format to a DateTime object?

Here is an example of the date format: ٢٠١٤-١٢-٢٨T٢١:٤١:٥٨Z

For the curious, it should translate to: 2014/12/28 21:41:58

Yodacheese
  • 4,787
  • 5
  • 34
  • 42
  • You can pass `CultureInfo` instance when using `DateTime.TryParse` or `DateTime.Parse` methods. If you know what language it is in just instantiate proper `CultureInfo` and should work. – MarcinJuraszek Dec 28 '14 at 23:10
  • @MarcinJuraszek I tried that with an Arabic culture info (ar-IQ) but it's throwing a String was not recognized as a valid DateTime exception. – Yodacheese Dec 28 '14 at 23:13
  • How do you obtain this value? Is the device supposed to use Unicode, or are you reading something in the wrong way? – CodeCaster Dec 28 '14 at 23:13
  • @CodeCaster I get it as a string from an external application. – Yodacheese Dec 28 '14 at 23:14
  • 4
    The .NET Framework only supports Arabic numerals in dates. Hehe. – Hans Passant Dec 28 '14 at 23:19

1 Answers1

3

Combining How to convert Arabic number to int? and How to create a .Net DateTime from ISO 8601 format:

static void Main(string[] args)
{
    string input = "٢٠١٤-١٢-٢٨T٢١:٤١:٥٨Z";
    string output = ReplaceArabicNumerals(input);

    var dateTime = DateTime.Parse(output, null, DateTimeStyles.AssumeUniversal);

    Console.WriteLine(output);
    Console.WriteLine(dateTime.ToString("u"));

    Console.ReadKey();
}

public static string ReplaceArabicNumerals(string input)
{
    string output = "";
    foreach (char c in input)
    {
        if (c >= 1632 && c <= 1641)
        {
            output += Char.GetNumericValue(c).ToString();
        }
        else
        {
            output += c;
        }                
    }
    return output;
}

Yields 2014-12-28T21:41:58Z and 2014-12-28 21:41:58Z.

Explanation of the ReplaceArabicNumerals() method: when it detects an Arabic-Indic numeral (between code point 1632 (0) and 1641 (9)), it requests the numerical value of the character. This translates the East-Arabic numerals into West-Arabic ones that .NET can parse.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272