DateTime ToString(“dd/MM/yyyy”) returns dd.MM.yyyy

I have also tried shielding the ‘/’ symbol in the formatting string, but it didn’t quite work. My final goal is to get the date with the ‘/’ symbols as separators. I guess I can use DateTime.ToString(“dd/MM/yyyy”).Replace('.', '/'), but that feels a bit excessive.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The / character in date/time format strings stands for “whatever the date separator of the format provider is”. Since you do not supply a format provider Thread.CurrentCulture is used, and in your case the current culture uses . as the date separator.

If you want to use a literal slash, place it inside single quotes:

dateTime.ToString("dd'/'MM'/'yyyy");

Alternatively, you could specify a format provider where the date separator is /:

dateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

All of the above is documented on MSDN.

See the difference in a live example.

Method 2

string s = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture)

Method 3

This is because of the way ToString works by default, in accordance with the current culture:

This method uses formatting information derived from the current
culture.

So, override that:

string date = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture)

Method 4

This works (note the InvariantCulture):

DateTime.Now.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)

If a CultureInfo is not specified, the CurrentCulture will be used. If this is a culture that doesn’t use slashes as separators in dates it is replaced by whatever the actual culture date separator is.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x