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.
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.
This solution is broken because Persian Calendar months have a different number of days than Gregorian months