C#无法正常工作

C#无法正常工作

本文介绍了Datetime.ToString()C#无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我期望 2015年7月29日,但收到了 2015年7月29日 !!!为什么?

解决方案

看起来像您的 /library/system.globalization.cultureinfo.currentculture%28v=vs.110%29.aspx> CurrentCulture -,这就是 / 字符替换为它的原因。



的特殊含义是用当前的区域性或提供的区域性日期分隔符替换我。



您有几种选择,要么逃避用单引号(或逐字字符串中的 \ / )或使用以 / 作为 DateSeparator ,例如。

  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);


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.

I was expecting 7/29/2015 but received 7-29-2015 !!! why?

解决方案

Looks like your DateSeparator of your CurrentCulture is - and that's why / character replace itself to it.

"/" 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.

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);

这篇关于Datetime.ToString()C#无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 10:43