Wes P
Wes P

Reputation: 9870

.NET DateTime.ToString() - Default Format Setting

Is the default format of ToString dependent on anything server related? Here's the issue: I'm testing and have tested an application on my local machine and ToString(), by default, is returning in a format of "MM/dd/yyyy hh:mm:ss tt", however on our server it appears to be returning as "dd/MM/yyyy hh:mm:ss tt" which the consuming application is not expecting and causing errors.

Dim uvExpireDate = DateTime.Now.AddMinutes(1)
Dim token = String.Format(fmtString, uvExpireDate.ToUniversalTime().ToString(), [various other params])

Thanks in advance for your help.

Upvotes: 3

Views: 18165

Answers (3)

DOK
DOK

Reputation: 32851

MSDN shows how to use code to set the culture if you can't change it on the server (Law of Unintended Consequences might apply):

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

public class FormatDate
{
   public static void Main()
   {
      DateTime dt = DateTime.Now;
      // Sets the CurrentCulture property to U.S. English.
      Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
      // Displays dt, formatted using the ShortDatePattern
      // and the CurrentThread.CurrentCulture.
      Console.WriteLine(dt.ToString("d"));

      // Creates a CultureInfo for German in Germany.
      CultureInfo ci = new CultureInfo("de-DE");
      // Displays dt, formatted using the ShortDatePattern
      // and the CultureInfo.
      Console.WriteLine(dt.ToString("d", ci));
   }
}

Upvotes: 0

Gerhard Powell
Gerhard Powell

Reputation: 6185

The computer "Region and Language Options" (Control Panel) specify the Date Format.

You can hardcode the date format: For Example:

uvExpireData.ToString(@"yyyyMMdd HH.mm.ss")

Upvotes: 0

Oded
Oded

Reputation: 499382

The formatting depends on the default Culture defined on the server.

If you want a specific Culture to apply, you need to use an overload that takes an IFormatProvider, or set the current thread Culture and UICulture to the wanted Culture.

InvariantCulture is a Culture that represents no specific culture but is based on en-US, so may be suitable for your use:

uvExpireDate.ToUniversalTime().ToString(CultureInfo.InvariantCulture)

So, the whole line would be:

Dim token = String.Format(fmtString, _ 
            uvExpireDate.ToUniversalTime().ToString(CultureInfo.InvariantCulture), _ 
            [various other params])

Upvotes: 7

Related Questions