c# Date component bug 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");
Mes开发者_开发技巧sageBox.Show(yearmonthday);
the problem is, C# uses the system date separator instead of always using "/" as i specified. If I run that code, I get the following output:
2011/03/18
but if I go to "control panel" -> "regional and language options" and change the date separator to "-", I get
2011-03-18
Even if in the toString method I specified to use '/' . Am I missing something or this is a C# / .Net Framework bug?
The /
in your format string is a placeholder for the date separator -- the behaviour that you're seeing is by design and clearly documented.
If you need a literal /
then you need to escape it in your format string, which should then look something like "yyyy\/MM\/dd" or "yyyy'/'MM'/'dd".
Try like this:
String yearmonthday = date.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
or escape the /
String yearmonthday = date.ToString(@"yyyy\/MM\/dd");
The problem is that / is reserved for the date character - so this isn't a bug - it's a feature that this gets interpreted according to the locale.
Try escpaing the / character with:
var d = DateTime.Now;
d.ToString("yy\\/mm\\/dd").Dump();
InvariantCulture
should do the trick
String yearmonthday = DateTime.Now.ToString("yyyy/MM/dd",CultureInfo.InvariantCulture);
You can get '-' or ":" based on the formats that you supply . refer http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx
the / is a date separator:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
if you need custom separator:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#dateSeparator
so the behavior is correct
You can escape the /
character, since it is the date separator, like this:
var d = DateTime.Now;
var s = d.ToString(@"yyyy\/MM\/dd");
Read all about it: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
This is apparently by design.
The work is implemented in an internal class called DateTimeFormat
which you can see this snippet in FormatCustomized
method:
case '/':
{
outputBuffer.Append(dtfi.DateSeparator);
num2 = 1;
continue;
}
So it replaces /
with DateSeparator
.
精彩评论