简体   繁体   中英

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.

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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