从基于当前系统区域性的字符串值生成日期时间
本文关键字:日期 时间 字符串 于当前 系统 区域性 | 更新日期: 2023-09-27 18:32:33
我需要的是使用字符串变量基于当前的系统区域性构建 DateTime。
一些例子说要手动完成
// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)
但是有没有办法自动做到这一点?
这段代码是否正确?
DateTime dateValue;
CultureInfo culture = CultureInfo.CurrentCulture;
DateTimeStyles styles = DateTimeStyles.None;
string strDateTime = string.Format("{0}/{1}/{2} {3}:{4}:{5}", systemTime.month, systemTime.day, systemTime.year, systemTime.hour, systemTime.minute, systemTime.second);
DateTime.TryParse(strDateTime, culture, styles, out dateValue);
只是对于需要它的人,我将把所有方法放在这里:
DateTime dateValue;
// Method 1
//CultureInfo culture = CultureInfo.CurrentCulture;
//DateTimeStyles styles = DateTimeStyles.None;
//string strDateTime = string.Format("{0}/{1}/{2} {3}:{4}:{5}", systemTime.month, systemTime.day, systemTime.year, systemTime.hour, systemTime.minute, systemTime.second);
//DateTime.TryParse(strDateTime, culture, styles, out dateValue);
// Method 2
//DateTime d = new DateTime(systemTime.year, systemTime.month, systemTime.day, systemTime.hour, systemTime.minute, systemTime.second);
//dateValue = DateTime.Parse(d.ToString("G"));
// Method 3 http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx The string s is parsed using formatting information in the current DateTimeFormatInfo object, which is supplied implicitly by the current thread culture.
DateTime d = new DateTime(systemTime.year, systemTime.month, systemTime.day, systemTime.hour, systemTime.minute, systemTime.second);
DateTime.TryParse(d.ToString(), out dateValue);
您可以通过将"G"
格式传递给ToString
来自动使用当前区域性:
string result = dt.ToString("G"); // 9/3/2008 4:05:07 PM for en-US
这是一个演示。
当您使用
DateTime.TryParse(string, out DateTime result)
时,它会自动使用当前区域性。请参阅此处的"备注"部分:http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx