Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting DateTime - ignore culture

Tags:

c#

I need to format a date to the following format:

M-d-yyyy

I tried using:

string.Format("{0:M-d-yyyy}", DateTime.Now)

But the output string will depend on the CurrentCulture on the computer where it's run, so sometimes the output might be 07/09/2014 or 07.09.2014 instead of 09-07-2014.

How can I easily prevent it from converting it based on the culture and treating it as a literal string?

like image 959
cogumel0 Avatar asked Jul 09 '14 18:07

cogumel0


People also ask

What does CultureInfo invariantculture mean?

The invariant culture is culture-insensitive; it is associated with the English language but not with any country/region. You specify the invariant culture by name by using an empty string ("") in the call to a CultureInfo instantiation method. CultureInfo.

How do I convert a DateTime to a specific format?

The ToString() method of the DateTime class is used to convert a DateTime date object to string format. The method takes a date format string that specifies the required string representation.

What is DateTime string Z?

“Z” is kind of a unique case for DateTimes. The literal “Z” is actually part of the ISO 8601 DateTime standard for UTC times. When “Z” (Zulu) is tacked on the end of a time, it indicates that that time is UTC, so really the literal Z is part of the time.

How do I change the default date format in C#?

var ci = new CultureInfo("en-US"); ci. DateTimeFormat. ShortDatePattern = "MM/dd/yyyy"; app.


2 Answers

Use CultureInfo.InvariantCulture as the culture or provider argument.

String.Format(CultureInfo.InvariantCulture, "{0:M-d-yyyy}", DateTime.Now)
like image 98
Daniel A. White Avatar answered Oct 19 '22 14:10

Daniel A. White


Use CultureInfo.InvariantCulture as an IFormatProvider parameter:

DateTime.Now.ToString("M-d-yyyy", CultureInfo.InvariantCulture);
like image 23
Willem Van Onsem Avatar answered Oct 19 '22 14:10

Willem Van Onsem