Yawar
Yawar

Reputation: 1943

convert arabic date string to datetime object in c#

I have date time in string format coming from server which I can't change.

DateTime is coming in this format and is in Arabic :

14-يوليه-2015 04:44:51 م

and I am unable to convert it in datetime object in c#.

I have tried these so far.

DateTime latest = Convert.ToDateTime(latestTables.Result.StaticTable[i].dtUpdTime, new CultureInfo("en-US"));

DateTime latest = DateTime.ParseExact(latestTables.Result.StaticTable[i].dtUpdTime, "dd-t hh:mm:ss yyyy-MMM", CultureInfo.InvariantCulture); 

DateTime latest = Convert.ToDateTime(latestTables.Result.StaticTable[i].dtUpdTime, new CultureInfo("ar-SA"));

Upvotes: 0

Views: 3359

Answers (2)

Martin Liversage
Martin Liversage

Reputation: 106916

Having tried to paste Arabic date strings into my answer I have discovered that characters are sometimes reordered due to RTL issues. In particular a DateTime formatted using the format d-MMMM-yyyy hh:mm:ss tt will have the initial d- part moved to the end (to the left) which is exactly how the string in your question appear (e.g. from right to left: month, year, time, AM/PM specifier and then day which seems weird). So I assume that your string really uses the more natural format d-MMMM-yyyy hh:mm:ss tt.

The issue that you are having is that you need to use the correct calendar. You have tried to use the ar-SA culture but the default calendar for this is a Hirji calendar. You need to use a Gregorian calendar with the correct month names. To change the calendar you need to create a new CultureInfo and choose the correct calendar. In your case it seems that you need to use the "Localized" calendar at index 5 of the OptionalCalendars property:

var cultureInfo = CultureInfo.CreateSpecificCulture("ar-SA");
cultureInfo.DateTimeFormat.Calendar = cultureInfo.OptionalCalendars[5];

You can then parse your string using this code (where I create the string in a way that does not change it when I paste it into my browser):

var dateTimeString = new String(new[] {
  '1',
  '4',
  '-',
  'ي',
  'و',
  'ل',
  'ي',
  'و',
  '-',
  '2',
  '0',
  '1',
  '5',
  ' ',
  '0',
  '4',
  ':',
  '4',
  '4',
  ':',
  '5',
  '1',
  ' ',
  'م'
});
var dateTime = DateTime.Parse(dateTimeString, cultureInfo);

The resulting DateTime is:

2015-07-14T16:44:51

If you want to use DateTime.ParseExact the format is d-MMMM-yyyy hh:mm:ss tt:

var dateTime = DateTime.ParseExact(dateTimeString, "d-MMMM-yyyy hh:mm:ss tt", cultureInfo);

You should also consider using DateTime.TryParse or DateTime.TryParseExact for better flow of code if you encounter an invalid formatted string.

Upvotes: 3

tichra
tichra

Reputation: 553

This text translates to "14 - July 04:44:51 -2015 m" according to google translate : Google Tranlate Link. You can easily parse this using DateTime.ParseExact

This question might help further

Upvotes: 0

Related Questions