cogumel0
cogumel0

Reputation: 2661

Formatting DateTime - ignore culture

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?

Upvotes: 11

Views: 12385

Answers (6)

David Zhou
David Zhou

Reputation: 142

You can set the culture of your program with this:

Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;`

You can also use a specific culture if you want (I think en-US is the one you need)

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

Use CultureInfo.InvariantCulture as an IFormatProvider parameter:

DateTime.Now.ToString("M-d-yyyy", CultureInfo.InvariantCulture);

Upvotes: 9

Alexander Bell
Alexander Bell

Reputation: 7918

Use the following:

DateTime.Now.ToString("d", DateTimeFormatInfo.InvariantInfo);

or apply other formatting specs as detailed in http://msdn.microsoft.com/en-us/library/az4se3k1%28v=vs.110%29.aspx

Pertinent to your case it could be written as:

DateTime.Now.ToString("M-d-yyyy", DateTimeFormatInfo.InvariantInfo);

Regards,

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190907

Use CultureInfo.InvariantCulture as the culture or provider argument.

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

Upvotes: 12

China Syndrome
China Syndrome

Reputation: 993

you can try date.ToString("MM/dd/yy", yyyymmddFormat);

or try whats in this link http://social.msdn.microsoft.com/Forums/en-US/af4f5a1e-f81d-47fe-981d-818e785b8847/convert-string-to-datetime-object

you can force the string into a standard format if you like

Upvotes: -1

entropic
entropic

Reputation: 1683

You can use the .ToString() method on the DateTime object to format it however you'd like. Your code would look something like this:

DateTime.Now.ToString("M-d-yyyy");

More info on formatting date times can be found on the MSDN: http://msdn.microsoft.com/en-us/library/zdtaw1bw%28v=vs.110%29.aspx

Upvotes: -1

Related Questions