What's up with DateTime.ToString() and the date separator?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Here's a mystery. (Using WinXP Pro) When the date separator in Control Panel
| Regional and Language options | Customize | Date is set to "/" (slash) the
following lines produce the expected output, but when the date separator is
"-" (hyphen), both statements produce output with hyphens as date separators.

System.Console.WriteLine ( System.DateTime.Now.ToString (
"yyyy-MM-dd HH:mm:ss" ) ) ;
System.Console.WriteLine ( System.DateTime.Now.ToString (
"yyyy/MM/dd HH:mm:ss" ) ) ;

It seems to me there's something wrong there. As I want to be able to
specify the separator in the ToString() I have to leave my computer set to
the slash separator.

One reason I need to be able to specify at run time is because some dates
get passed to apps and I want to use ISO8601 formats (using the hyphen) and
other times I need to format a parameter for SCHTASKS (the /SC parameter
requires the date to use slashes as separators, why is that by the way?)

In my opinion, when the programmer specifies the format string as above, the
date separator setting in control panel should not affect the output. Only
when no format is specified ( also with ToLongDateString() and
ToShortDateString() ) should the control panel setting be used.

Or is there something I'm missing?
 
PIEBALD said:
Here's a mystery. (Using WinXP Pro) When the date separator in Control Panel
| Regional and Language options | Customize | Date is set to "/" (slash) the
following lines produce the expected output, but when the date separator is
"-" (hyphen), both statements produce output with hyphens as date separators.

System.Console.WriteLine ( System.DateTime.Now.ToString (
"yyyy-MM-dd HH:mm:ss" ) ) ;
System.Console.WriteLine ( System.DateTime.Now.ToString (
"yyyy/MM/dd HH:mm:ss" ) ) ;

It seems to me there's something wrong there.

There's nothing wrong at all. "/" means "date separator", just as
documented in the custom DateTime format strings page.

If you want to use the exact literal "/", put it in quotes:
"yyyy'/'MM'/'dd HH:mm:ss".
 
Back
Top