开发者

C# DateTime.ToString with data format or pattern

开发者 https://www.devze.com 2022-12-14 03:41 出处:网络
i am trying to understand how DateTime.ToString(Date pattern) work in .net framework, C#. I changed my computer to have a short Date format like this yyyy.MM.dd.

i am trying to understand how DateTime.ToString(Date pattern) work in .net framework, C#.

I changed my computer to have a short Date format like this 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

and

myDate.ToString("yyyy-MM-dd") does return string in the format of 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

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.

Read the information on the format specifiers:

/ = The default date separator defined in DateSeparator.


You can also escape single character using backslash:

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消