简体   繁体   中英

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.

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);

Try to solve your problem with this:

string myTime = DateTime.Parse("01/02/2016")
                        .ToString(CultureInfo.GetCultureInfo("en-GB").DateTimeFormat.ShortDatePattern);

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