S. Richter S. Richter - 1 month ago 14
C# Question

How to make DateTime independent from the current culture?

I cam trying to convert a datetime to string and back, but making it so that it works for all cultures.

I basically have a Textbox (tbDateTime) and a label (lbDateTime). The label tells the user, in which format the software expects the input of tbDateTime. The input of the Textbox will be used for an MySQL command.

Currently it works like this:

lbDateTime.Text = "DD.MM.YYYY hh:mm:ss"; // I live in germany
DateTime date = Convert.ToDateTime(tbDateTime.Text);
String filter = date.ToString("yyyy-MM-dd HH:mm:ss");


Now my question:


  • Is it possible to determine the format-string for lbDateTime.Text based on the current culture?

  • Which format does the Convert.ToDateTime function uses?



I hope you can help me. I have actually no pc here to test different cultures, so I'm very afraid that I make something wrong.

Answer

Instead of using the Convert.ToDateTime method you can use the DateTime.Parse or DateTime.ParseExact methods. Both allow you to pass a culture that tells how you expect the date to be formatted.

The DateTime.ParseExact method also allows you to specify the format you expect, so you can parse more or less any format with this method.

Edit:
Regarding Convert.ToDateTime. The documentation says that the current culture is used when parsing: http://msdn.microsoft.com/en-us/library/xhz1w05e.aspx

The current culture can be found using the System.Threading.Thread.CurrentThread.CurrentCulture property.

Edit2:
Oh. You may also want to use DateTime.TryParse and DateTime.TryParseExact if you are unsure whether the given format is invalid.

Edit3:
Lots of edits here... I see that you want to determine the culture string that matches the date the user has entered. There is no general solution that is guaranteed to work here. Say for instance that the user has entered the date 01.02.11. There is no way to be certain if this date is in day.month.year or month.day.year or year.month.day and so on.

The best you can do is to have a list of expected input cultures and start with the most likely and try to parse the date using that. If that fails, you can try the second most likely and so on...

But this is really not recommended. Either give the user an expected format, or better, use a date input box that ensures that you receive the selected date in an appropriate format.