Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Wrong DateTime Format

I have this:

var dateString = string.Format("{0:dd/MM/yyyy}", date);

But dateString is 13.05.2011 instead of 13/05/2011. Can you help me?

like image 533
karaxuna Avatar asked Jan 31 '26 08:01

karaxuna


1 Answers

You could use DateTime.ToString with CultureInfo.InvariantCulture instead:

var dateString = date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

The reason why / is replaced with . is that / is a custom format specifier

The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfo.DateSeparator property of the current or specified culture.

So either use InvariantCulture which uses / as date separator or - more appropriate - escape this format specifier by embedding it within ':

var dateString = date.ToString("dd'/'MM'/'yyyy");

Why this is more appropriate? Because you can still apply the local culture, f.e. if you want to output the month names, but you force / as date separator anyway.

like image 119
Tim Schmelter Avatar answered Feb 01 '26 22:02

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!