Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string Persian date to Gregorian DateTime

To convert a string Persian date to gregorian DateTime, I use date time picker and it sends me a string like "۱۳۹۴/۰۲/۲۰"

PersianCalendar p = new PersianCalendar();               
string[] d = start.Split('/');           
DateTime dt = new DateTime(int.Parse(d[0]), 
                           int.Parse(d[1]),
                           int.Parse(d[2]),
                           new HijriCalendar());

and my function that converts is

public static DateTime ToGregorianDate(this DateTime dt)
{
     PersianCalendar pc = new PersianCalendar();
     return pc.ToDateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, 0, 0);    
}

It gives DateTime how can I send correct DateTime when it wants to convert shows this error:

Input string was not in a correct format.

like image 472
aliyousefian Avatar asked Apr 30 '15 06:04

aliyousefian


2 Answers

You have two different problems:

  • Arabic digits aren't supported by DateTime parsing

  • PersianCalendar isn't part of any CultureInfo, so you can't use it directly while parsing the string to DateTime (and you can't set it to a preexisting CultureInfo).

Possible solution:

string date = "۱۳۹۴/۰۲/۲۰";
string date2 = Regex.Replace(date, "[۰-۹]", x => ((char)(x.Value[0] - '۰' + '0')).ToString());

Replace the digits from Arabic to decimal

DateTime dt = DateTime.ParseExact(date2, "yyyy/MM/dd", CultureInfo.InvariantCulture);

Then parse the date ignoring the calendar

PersianCalendar pc = new PersianCalendar();
DateTime dt2 = pc.ToDateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);

Then convert the date to the right calendar.

like image 145
xanatos Avatar answered Oct 21 '22 02:10

xanatos


As I commented; Eastern Arabic numerals does not supported by DateTime parsing methods, it only accepts Arabic numerals.

However, char type has a GetNumericValue method which converts any numeric Unicode character to a double.

Let's use a combination of char.GetNumericValue, string.Join and Int32.Parse methods;

string d = "۱۳۹۴/۰۲/۲۰";
int year = Int32.Parse(string.Join("", 
    d.Split('/')[0].Select(c => char.GetNumericValue(c)))); // 1394
int month = Int32.Parse(string.Join("", 
    d.Split('/')[1].Select(c => char.GetNumericValue(c)))); // 2
int day = Int32.Parse(string.Join("", 
    d.Split('/')[2].Select(c => char.GetNumericValue(c)))); // 20

And then you can create a DateTime based on this values;

DateTime dt = new DateTime(year, month, day);

Then you can use;

PersianCalendar pc = new PersianCalendar();
var dt1 = pc.ToDateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);
// {10.05.2015 00:00:00}
like image 5
Soner Gönül Avatar answered Oct 21 '22 04:10

Soner Gönül