简体   繁体   English

Datetime.ToString() C# 没有按预期工作

[英]Datetime.ToString() C# not working as expected

From msdn it seems like I can create my own format with Datetime.ToString() method by using M, m, d, y etc. But when I tried one it didn't worked as expected, snipped below is the issue.msdn看来,我可以通过使用M, m, d, y等方法使用Datetime.ToString()方法创建我自己的格式。但是当我尝试一个时,它没有按预期工作,下面是问题所在。

在此处输入图片说明

I was expecting 7/29/2015 but received 7-29-2015 !!!我期待7/29/2015但收到7-29-2015 !!! why?为什么?

Looks like your DateSeparator of your CurrentCulture is - and that's why / character replace itself to it.看起来您的CurrentCultureDateSeparator-这就是为什么/字符将自身替换为它的原因。

"/" custom format specifier has a special meaning as replace me with current culture or supplied culture date separator. "/"自定义格式说明符具有特殊含义,用当前文化或提供的文化日期分隔符替换我。

You have a few options, you either escape it with single quotes (or \\/ in a verbatim string literal) or use a culture that has / as a DateSeparator like InvariantCulture .您有几个选择,您可以使用单引号(或逐字字符串文字中的\\/对其进行转义,或者使用具有/作为DateSeparator的文化,如InvariantCulture

string s = DateTime.Now.ToString("M'/'d'/'yyyy");
string s = DateTime.Now.ToString(@"M\/d\/yyyy");
string s = DateTime.Now.ToString("M/d/yyyy", CultureInfo.InvariantCulture);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM