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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With