C # Date component error, or am I missing something?

I have a huge problem with the following code:

DateTime date = DateTime.Now; String yearmonthday = date.ToString("yyyy/MM/dd"); MessageBox.Show(yearmonthday); 

the problem is that C # uses a system date separator instead of always using "/" as I pointed out. If I run this code, I get the following output:

 2011/03/18 

but if I go to "control panel" β†’ "regional and language settings" and change the date separator to "-", I get

 2011-03-18 

Even if in the toString method I indicated to use '/'. Am I missing something or is it a C # /. Net Framework error?

+6
c # datetime
source share
8 answers

/ in your format string, the placeholder for the date separator β€” the behavior you see β€” is design and clearly documented.

If you need the literal / , then you need to avoid it in the format string, which then should look something like this: "yyyy \ / MM \ / dd" or "yyyy '/' MM '/' dd".

+5
source share

Try it like this:

 String yearmonthday = date.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture); 

or exit /

 String yearmonthday = date.ToString(@"yyyy\/MM\/dd"); 
+5
source share

The problem is that / is reserved for the date character - so this is not an error - it is a function that is interpreted according to the locale.

Try using the / symbol with:

 var d = DateTime.Now; d.ToString("yy\\/mm\\/dd").Dump(); 
+3
source share

InvariantCulture should do the trick

 String yearmonthday = DateTime.Now.ToString("yyyy/MM/dd",CultureInfo.InvariantCulture); 
+2
source share

You can get "-" or ":" based on the formats you supply. contact http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx

+1
source share

/ is a date separator:

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

if you need a special delimiter:

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#dateSeparator

therefore, the behavior is correct

+1
source share

You can avoid the / character, as it is a date separator, for example:

 var d = DateTime.Now; var s = d.ToString(@"yyyy\/MM\/dd"); 

Read all about it: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

+1
source share

This is apparently by design.

Work is done in the internal DateTimeFormat class, which you can see in this FormatCustomized method:

  case '/': { outputBuffer.Append(dtfi.DateSeparator); num2 = 1; continue; } 

Thus, it replaces / with DateSeparator .

+1
source share

All Articles