Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.Format Date conversion issue

Tags:

c#

datetime

I am using Windows 8. My culture is "en-IN". but format for date time is MM/dd/yyyy
When trying

String.Format("{0:MM/dd/yyyy}", DateTime.Today);

gives format like 12-29-2012.

Please suggest how can I do.

like image 812
Hardik Fefar Avatar asked Jun 20 '26 02:06

Hardik Fefar


2 Answers

It's not clear what the problem is. If it's just that it's using hyphens instead of slashes, that's presumably because the default date separator for your culture is a hyphen. The options are:

  • Explicitly specify a different culture (e.g. the invariant culture)

    String.Format(CultureInfo.InvariantCulture, "{0:MM/dd/yyyy}", DateTime.Today);
    
  • Escape the slashes:

    String.Format("{0:MM'/'dd'/'yyyy}", DateTime.Today);
    

Note that using DateTime.Today.ToString(...) would be simpler than using string.Format IMO.

like image 118
Jon Skeet Avatar answered Jun 22 '26 16:06

Jon Skeet


Well, yeah - your current culture is used for a lot of format-related settings;

Here, try this:

// Change culture
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-IN");
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-IN");

// prints 12-29-2012
Console.WriteLine(string.Format("{0:MM/dd/yyyy}", DateTime.Today));

// Invariant culture, so ignore any culture-based settings
// prints 12/29/2012
Console.WriteLine(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:MM/dd/yyyy}", DateTime.Today));
like image 31
JerKimball Avatar answered Jun 22 '26 15:06

JerKimball