Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime Format in C#

Tags:

c#

.net-3.5

wpf

I experiencing a strange behavior of C#. Its some thing like this..

var date = DateTime.Now.ToString("MM/dd/yyyy");

I expecting out to be

04/24/2009

but in actuall its returning

04-24-2009

and my OS culture is en-GB, I'm using .Net 3.5 and WPF

any solutions please... ???

like image 659
Prashant Cholachagudda Avatar asked Apr 24 '09 13:04

Prashant Cholachagudda


People also ask

What is T and Z in DateTime C?

A UTC DateTime is being converted to text in a format that is only correct for local times. This can happen when calling DateTime. ToString using the 'z' format specifier, which will include a local time zone offset in the output.

Is DateTime a string format?

A date and time format string defines the text representation of a DateTime or DateTimeOffset value that results from a formatting operation. It can also define the representation of a date and time value that is required in a parsing operation in order to successfully convert the string to a date and time.


3 Answers

According to the MSDN docs for custom date and time format strings, / is a placeholder:

Represents the date separator defined in the current DateTimeFormatInfo.DateSeparator property. This separator is used to differentiate years, months, and days.

If you want a definite slash, use "MM'/'dd'/'yyyy":

DateTime.Now.ToString("MM'/'dd'/'yyyy")
like image 113
Jon Skeet Avatar answered Oct 04 '22 16:10

Jon Skeet


It uses the separator set up in the regional settings, since "/" is the substitute character for the separator.

You can create your own DateTimeFormat instance with different separators.

like image 28
Lucero Avatar answered Oct 04 '22 17:10

Lucero


Try calling ToString on the date itself and passing the CultureInfo.InvariantCulture object:

string date = yourDate.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture));
like image 31
Justin Niessner Avatar answered Oct 04 '22 17:10

Justin Niessner