0

What I need is to use string variables to build DateTime based on the current system culture.

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)

But is there a way to do it automatically?

Is this code correct?

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

Just for someone who needs it I will put all methods here:

 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 Answers 2

2

You can use the current culture automatically by passing the "G" format to ToString:

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

Here's a demo.

1

When you use DateTime.TryParse(string, out DateTime result) it automatically uses the current culture. See the Remarks section here: http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.