1

Assuming I have a DateTime object in C#, and the date is 3rd of january 2011.

In some locales it would be 03/01/2011 and in some it would be 01/03/2011

How can I get computer's regional settings in order to show the datetime.toString() the appropriate value?

Rahul Gokani
  • 1,688
  • 5
  • 25
  • 43
buddy123
  • 5,679
  • 10
  • 47
  • 73
  • 2
    Related http://stackoverflow.com/questions/1542409/how-to-get-current-regional-settings-in-c – Soner Gönül Jul 09 '13 at 11:31
  • What I intended to say in my answer (deleted after getting -2 in less than 15 sec, really quick people here :)) is that perhaps you should rely on a hardcoded format highlighting clearly what is what. For example: 3-Jan-2011 or Jan-3-2011; and, eventually, include an option for users to change the format. There are many users which are not even aware about the exact regional settings on their computer. Relying blindly on this might drive to unclear situations like 1-3-2011 for a computer with US settings which might be misundertood because the program was created in the UK. – varocarbas Jul 09 '13 at 11:46

3 Answers3

2

The DateTime.ToString() method, without a parameter, automatically uses the G format parameter which takes culture into account. See here and here for details.

Tim Copenhaver
  • 3,282
  • 13
  • 18
1

DateTime.ToString() without parameters actually uses the current culture. So the output of .ToString() will be different on multiple machines, depending on their culture.

ken2k
  • 48,145
  • 10
  • 116
  • 176
  • thanks. I try to change my reginal settings by going to Region and Language -> Format:.." and change it to something else, but i always get with ToString a dd/mm/yyyy date. What am I missing? – buddy123 Jul 09 '13 at 11:49
  • Are you restarting your program after changing settings? I dunno but reckon the current culture info is likely cached first at process level, and then used to initialize every thread runnable in that process. – The Dag Jul 09 '13 at 11:51
  • Ok. correct. one last thing, is it possible to make only the years 2digits, as i could do dd/mm/yy, but let the dd/mm to be arranged according to regional settings? – buddy123 Jul 09 '13 at 11:57
1

You can use String.Format with current culture into to do that:

String.Format(CultureInfo.CurrentCulture, "{0}", DateTime.Now)

Also if you want to change for a different culture you can do the following:

String.Format(new CultureInfo("en-IN"), "{0}", DateTime.Now)

Output: 7/9/2013 5:04:33 PM 09-07-2013 17:04:34

seshuk
  • 182
  • 4