Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert DateTime in different System culture?

I need to convert DateTime value in different culture format, whatever set in system.

There is not any specific TimeZone selected for converting, any culture format was using converting DateTime value.

DateTimeFormatInfo ukDtfi = new CultureInfo(CultureInfo.CurrentCulture.ToString(), false).DateTimeFormat;
StartingDate = Convert.ToDateTime(System.Web.HttpContext.Current.Session["StartDate"].ToString(), ukDtfi);

I am using above code but its not working properly. Currently I set ar-SA culture in my system.

like image 991
Jeet Bhatt Avatar asked Dec 07 '25 05:12

Jeet Bhatt


2 Answers

Let me clear some subjects first..

A DateTime instance does not have any timezone information and culture settings. It just have date and time values. Culture settings concept only applies when you get it's textual (string) representatiton.

Since you use ar-SA culture, your string format is not a standard date and time format for that culture.

var dt = DateTime.Parse("31/1/2016 12:00 AM", CultureInfo.GetCultureInfo("ar-SA"));
// Throws FormatException

And you can't parse this string with ar-SA culture because this culture uses ص as a AMDesignator since it uses UmAlQuraCalendar rather than a GregorianCalendar.

You can use InvariantCulture (which uses AM as a AMDesignator and uses GregorianCalendar) instead with DateTime.ParseExact method with specify it's format exactly.

string s = "31/1/2016 12:00 AM";
DateTime dt = DateTime.ParseExact(s, "dd/M/yyyy hh:mm tt", 
                                  CultureInfo.InvariantCulture);

which in your case;

StartingDate = DateTime.ParseExact(System.Web.HttpContext.Current.Session["StartDate"].ToString(), 
                                   "dd/M/yyyy hh:mm tt", 
                                   CultureInfo.InvariantCulture);
like image 144
Soner Gönül Avatar answered Dec 09 '25 18:12

Soner Gönül


Try to solve your problem with this:

string myTime = DateTime.Parse("01/02/2016")
                        .ToString(CultureInfo.GetCultureInfo("en-GB").DateTimeFormat.ShortDatePattern);
like image 27
Ferid Š. Sejdović Avatar answered Dec 09 '25 20:12

Ferid Š. Sejdović



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!