4

When I set the CurrentCulture, how can I override the date format that is set?

Example:

System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");

Say I wanted to override the default date format so whenever I output DateTime value it is by default in the format I want.

loyalflow
  • 14,275
  • 27
  • 107
  • 168

4 Answers4

7

First of all you need to create an instance of CultureInfo that won't be read only. Then you can create an instance of your DateTimeFormatInfo, configure it appropriately and finally assign it to your CultureInfo object:

var culture = CultureInfo.CreateSpecificCulture("en-US");
//or simply var culture = new CultureInfo("en-US");
var dateformat = new DateTimeFormatInfo();
//then for example: 
dateformat.FullDateTimePattern = "dddd, mmmm dd, yyyy h:mm:ss tt";
culture.DateTimeFormat = dateformat;
System.Threading.Thread.CurrentThread.CurrentCulture = culture;

The full specification on how to configure your DateTimeFormatInfo can be found here.

Paweł Bejger
  • 6,176
  • 21
  • 26
0

DateTime doesn't have format. Strings have. Sounds like you just need to use DateTime.ToString() method like;

CultureInfo culture = CultureInfo("en-US");
DateTime.ToString("mm\/dd\/yyyy", culture);

Rememer The "/" Custom Format Specifier has a special meaning. If you want only / character, you should escape it. Take a look at my another answer.

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
0

No, you can't, because CultureInfo.GetCultureInfo returns a cached, read-only version.

What you can do is format a DateTime like you normally would, or create your own Culture, inheriting the behavior of your desired culture.

Codeman
  • 12,157
  • 10
  • 53
  • 91
0

Check out the ToString() method on DateTime:

DateTime thisDate1 = new DateTime(2011, 6, 10);
Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + ".");

There are many, many ways to format dates with patterns. Here is a reference:

http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

Mister Epic
  • 16,295
  • 13
  • 76
  • 147