简体   繁体   English

具有数据格式或模式的C#DateTime.ToString

[英]C# DateTime.ToString with data format or pattern

i am trying to understand how DateTime.ToString(Date pattern) work in .net framework, C#. 我试图了解DateTime.ToString(日期模式)如何在.net框架,C#中工作。

I changed my computer to have a short Date format like this yyyy.MM.dd. 我改变了我的计算机,使其具有像yyyy.MM.dd这样的简短日期格式。 Following is what I notice 以下是我注意到的

DateTime myDate = DateTime.Now;

myDate.ToString("yyyy/MM/dd") always return in the format of yyyy.MM.dd not yyyy/MM/dd myDate.ToString("yyyy/MM/dd")总是以yyyy.MM.dd的格式返回,而不是yyyy / MM / dd
and
myDate.ToString("yyyy-MM-dd") does return string in the format of yyyy-MM-dd myDate.ToString("yyyy-MM-dd")确实以yyyy-MM-dd的格式返回字符串

to have it return what i was looking for, this is what i need to do myDate.ToString("yyyy'/'MM'/'dd") ===> yyyy/MM/dd 让它返回我想要的东西,这就是我需要做的myDate.ToString("yyyy'/'MM'/'dd") ===> yyyy / MM / dd

Can anyone explain to me why it is doing that? 任何人都可以向我解释为什么这样做? and is there any other way i can achieve the same result? 还有其他方法可以达到相同的效果吗?

thanks.... 谢谢....

/ is considered a format specifier and is replaced just like yyyy is. /被认为是格式说明符,并且像yyyy一样被替换。

Read the information on the format specifiers : 阅读有关格式说明符的信息:

/ = The default date separator defined in DateSeparator. / = DateSeparator中定义的默认日期分隔符。

You're getting the behavior you're seeing because "/" is a format specifier . 您正在获得您所看到的行为,因为“/”是格式说明符

If you look at the custom date format settings help, you'll see that "/" translates as the date separator for your culture. 如果查看自定义日期格式设置帮助,您会看到“/”转换为您的文化的日期分隔符。

You can also escape single character using backslash: 您还可以使用反斜杠转义单个字符:

DateTime myDate = DateTime.Now;
myDate.ToString("yyyy\\/MM\\/dd");
// or
myDate.ToString(@"yyyy\/MM\/dd");

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

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