convert arabic date string to datetime object in c#

天涯浪子 提交于 2019-12-12 05:58:11

问题


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"));

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/31427498/convert-arabic-date-string-to-datetime-object-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!