How to convert DateTime in different System culture?

守給你的承諾、 提交于 2019-12-11 10:26:20

问题


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.


回答1:


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



回答2:


Try to solve your problem with this:

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


来源:https://stackoverflow.com/questions/35126433/how-to-convert-datetime-in-different-system-culture

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!