3

I would like to override the default behavior of the DateTime.ToSting() function so I can add it automatically the CultureInfo.

My final result is that if someone use the function like this:

DateTime.Now.ToString("g");

I can make it work like this:

DateTime.Now.ToString("g", new CultureInfo("en-US"));

It's a multi threaded application in .NET 4 Framework and I prefer not the set it on each thread.

David
  • 414
  • 1
  • 6
  • 16

2 Answers2

1

You can change the CultureInfo for the Current Thread, which will lead to changes you need. According MSDN, DateTime.ToString method uses formatting information derived from the current culture. For more information, see CurrentCulture.

So you can simply edit the CultureInfo.CurrentCulture property in thread you are using for creation other threads., and this will lead you to the behaviour you want.

MSDN example for multithreading and AppDomains:

using System;
using System.Globalization;
using System.Threading;

public class Info : MarshalByRefObject
{
   public void ShowCurrentCulture()
   {
      Console.WriteLine("Culture of {0} in application domain {1}: {2}",
                        Thread.CurrentThread.Name,
                        AppDomain.CurrentDomain.FriendlyName,
                        CultureInfo.CurrentCulture.Name);
   }
}

public class Example
{
   public static void Main()
   {
      Info inf = new Info();
      // Set the current culture to Dutch (Netherlands).
      Thread.CurrentThread.Name = "MainThread";
      CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("nl-NL");
      inf.ShowCurrentCulture();

      // Create a new application domain.
       AppDomain ad = AppDomain.CreateDomain("Domain2");
       Info inf2 = (Info) ad.CreateInstanceAndUnwrap(typeof(Info).Assembly.FullName, "Info");
       inf2.ShowCurrentCulture();                       
   }
}
// The example displays the following output: 
//       Culture of MainThread in application domain ChangeCulture1.exe: nl-NL 
//       Culture of MainThread in application domain Domain2: nl-NL

You can try to override the usage of the method via Microsoft Fakes or Moles or something similar tool, but this is not really recommended.

VMAtm
  • 27,943
  • 17
  • 79
  • 125
0

DateTime is a sealed struct so it cannot be inherited. One way to achieve this to use Extension:

public static class MyDateTimeExtension
{

    public static string ToMyCulture(this DateTime dt, CultureInfo info)
    {
         ...
    }
}

DateTime timeTest = DateTime.Now;
var myTimeString = timeTest.ToMyCulture(new CultureInfo("en-US"));
Joonas Koski
  • 269
  • 1
  • 5