简体   繁体   中英

string was not recognized as a valid datetime while Converting Date from Hijri to Gregorian date

I am Trying to Convert Hijri Date into Gregorian Date I was following this article and My Code is as follows :

var cultureInfo = CultureInfo.CreateSpecificCulture("ar-sa");
string date = "19/12/36 12:00:00 ص";

Getting

string was not recognized as a valid datetime

error in below line

DateTime tempDate = DateTime.ParseExact(date, "dd/MM/yyyy", cultureInfo.DateTimeFormat, DateTimeStyles.AllowInnerWhite);
lblDate.Text = tempDate.ToString("dd/MM/yyyy");

I am getting string was not recognized as a valid datetime. Please can somebody tell me whats wrong with this code?

I think I'm on the right way but.. Let's try something at least.

First of all, DateTime values are always in the Gregorian calendar, basically. There's no such thing as "A DateTime in a UmAlQuraCalendar calendar" - which is used by ar-sa culture - you have to use the UmAlQuraCalendar to interpret a DateTime in a particular way.

Second, when you use DateTime.ParseExact for parsing your string, your string and format does match exactly based on culture you use. Since ص character seems AMDesignator of ar-sa culture, you should provide tt specifier with your time part as well.

string s = "19/12/36 12:00:00 ص";
DateTime dt;
if(DateTime.TryParseExact(s, "dd/MM/yy hh:mm:ss tt", CultureInfo.GetCultureInfo("ar-sa"),
                          DateTimeStyles.None, out dt))
{
    Console.WriteLine(dt);
}

Note: Since TwoDigitYearMax is 1451 of UmAlQuraCalendar calendar, your 36 will be parsed as 1436 with yy format specifier.

This perfectly parse your question but WAIT! What will be the result? Here it is.

02/10/2015 00:00:00

Why? As I said in the top, you have to use the UmAlQuraCalendar to interpret this DateTime instance.

UmAlQuraCalendar ul = new UmAlQuraCalendar();
Console.WriteLine(ul.GetYear(dt)); // 1436
Console.WriteLine(ul.GetMonth(dt)); // 12
Console.WriteLine(ul.GetDayOfMonth(dt)); // 19

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM