In the screenshot DateTime.ToString() method is being called but the date is not getting formatted in expected format (as seen in Quick Watch widnow). Is something wrong ?
Asked
Active
Viewed 1,885 times
0
-
2You are giving it an explicit format and then expecting it to use the regional one? – Adam Houldsworth May 06 '14 at 16:11
-
Yeah. Looks like epic programmer fail. You do NOT call "ToString()", you call an overload that says exactly how you want this one formatted. – TomTom May 06 '14 at 16:12
-
What format do you want it in? – frenchie May 06 '14 at 16:12
-
No, I am expecting to get the format that is specified as parameter to ToString method. Showing the regional format just in case they are having any effect on the output. – Brij May 06 '14 at 16:13
-
@Brij Oh, so you are referring to the slashes turning into hyphens? – Adam Houldsworth May 06 '14 at 16:13
-
I want the date to be in the format as explicitly specified !!! – Brij May 06 '14 at 16:14
-
@AdamHouldsworth, yes you are correct, slashes are turning into hyphens. – Brij May 06 '14 at 16:15
-
1@Brij I am simply trying to make your question clearer, the screenshot is very small and truth be told, not entirely needed. You could have shown expected output versus actual and it would have been clearer. – Adam Houldsworth May 06 '14 at 16:15
-
@AdamHouldsworth, I had the same confusion. The question was not very clear. – Drew Noakes May 06 '14 at 16:21
-
@AdamHouldsworth Picture ain't that small. I am in Chrome, and can use Open in new tab and it is pretty good.. – Brij May 06 '14 at 16:23
3 Answers
4
You are using /
as separator in your ToString
format. But your current culture seems to has -
as date separator. That is why you see the difference. You can pass CultureInfo.InvariantCulture
with ToString
.
Like:
DateTimeObject.ToString("MM/dd/yyy HHmmss", CultureInfo.InvariantCulture)

Habib
- 219,104
- 29
- 407
- 436
-
1
-
@Habib, why did the `/` turn into `-`. Why are they being changed internally, despite being specified explicitly ? – Brij May 06 '14 at 16:21
-
@Brij [Here is the documentation](http://msdn.microsoft.com/en-us/library/8kb3ddd4%28v=vs.110%29.aspx#dateSeparator) – Sriram Sakthivel May 06 '14 at 16:22
-
@Brij, Sriram, has pointed to the right documentation, but just to add a one more thing, When you don't specify the culture in `ToString` then the current culture is used. You may see: http://stackoverflow.com/questions/2329297/net-are-there-any-differences-between-invariantculture-and-en-us – Habib May 06 '14 at 16:27
0
DateTime.ToString
replaces /
with the current date separator and :
with the current time separator. You're passing in the format yourself, and it does not match what's in the Region settings.
To use the Region settings, use ToShortDateString()
and ToShortTimeString()
.

Thorsten Dittmar
- 55,956
- 8
- 91
- 139
0
You can use this:
DateTime.now.ToString("yyyyMMddHHmmss");
or
DateTime.now.ToString("mm-dd-yyyy");

Ricardo Romo
- 1,588
- 12
- 25