2012-04-27 33 views
0

我需要的是使用字符串變量根據當前系統區域構建DateTime。基於當前系統區域的字符串值構建DateTime

Some example says to do it manually

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

回答

2

可以自動使用當前的文化通過傳遞the "G" formatToString

string result = dt.ToString("G"); // 9/3/2008 4:05:07 PM for en-US 

Here's a demo.