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?
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.
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.
“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.
var ci = new CultureInfo("en-US"); ci. DateTimeFormat. ShortDatePattern = "MM/dd/yyyy"; app.
Use CultureInfo.InvariantCulture
as the culture or provider argument.
String.Format(CultureInfo.InvariantCulture, "{0:M-d-yyyy}", DateTime.Now)
Use CultureInfo.InvariantCulture
as an IFormatProvider
parameter:
DateTime.Now.ToString("M-d-yyyy", CultureInfo.InvariantCulture);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With