sunil shankar
sunil shankar

Reputation: 277

datetime format : can a computer be forced to use a particular format?

I have developed a winform application that makes use of the format dd-MM-yyyy hh:mm:ss (24 hr system).

When I try the application on another computer, I get an error, because the standard datetime format there is dd/MM/yyyy hh:mm:ss am/pm.

Moreover, the controls in which the datetime is stored, also hold the datetime string in a different format: d/M/yyyy hh:mm:ss am/pm, eg 1/4/2013 12:00:00 A.M. instead of 01/04/2013 12:00:00 A.M.

Can I force the other system to somehow use the same format? I am a novice here. Thanks for the help.

Upvotes: 1

Views: 2588

Answers (3)

Kai
Kai

Reputation: 2013

I would not recommend to force the system to one date and time format. From my point of view the better question would be, why is your application using a specified format? The .NET Framework is designed that you don't have to care about such things.

Anyway, if you will really force the system to display the data in a specified format, change the thread culture:

System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("de-DE")

System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-DE")

Upvotes: 0

Wouter de Kort
Wouter de Kort

Reputation: 39898

When displaying a DateTime object, there are two things to keep in mind.

  • Culture settings: when you don't specify an explicit culture, the culture that's set by the system your application is running on is used.
  • Format strings: when converting a DateTime object to a string, you can give it a format string as an argument that specifies how your DateTime object should be formatted. Something like: "d" for a short date pattern or "t" to only display the time.

Combining these two will give you full control over how to display your DateTime objects. You should however be careful in forcing a certain culture setting on the user. If your application should support globalization (so multiple users from different cultures can use your app) you shouldn't depend on a specific culture. Instead, you should store all your data culture-insensitive and format it with the users culture when you display it on screen.

Here is an example how to use both the CultureInfo object and a format string:

string myDate = "10-05-2013 08:52:30";
DateTime date = DateTime.Parse(myDate);

Console.WriteLine(date.ToString("d", new CultureInfo("en-US"))); // 5/10/2013
Console.WriteLine(date.ToString("d", new CultureInfo("nl-NL"))); // 10-5-2013

Console.WriteLine(date.ToString("f", new CultureInfo("nl-NL"))); // vrijdag 10 mei 2013 08:52

Upvotes: 3

Marco van Kimmenade
Marco van Kimmenade

Reputation: 398

You should be able to set the culture for the application to the one you need to use.

System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("EN");

Upvotes: 1

Related Questions