[英]DateTime: how to display as DD.MM.YYYY?
I've got DateTime variable and i want to convert it to string "DD.MM.YYYY" Please note, the values must be separated by "dot" sign. 我有DateTime变量,我想将其转换为字符串“DD.MM.YYYY”请注意,值必须用“点”符号分隔。
Of course I can do manual string composition. 当然我可以做手工字符串组合。 But I wonder if I can use
DateTime.ToString()
to do required conversion. 但我想知道我是否可以使用
DateTime.ToString()
来进行必要的转换。
Yes, you can: 是的你可以:
string formatted = dt.ToString("dd'.'MM'.'yyyy");
Now in this case the quotes aren't actually required, as custom date/time format strings don't interpret dot in any special way. 现在在这种情况下,实际上并不需要引号,因为自定义日期/时间格式字符串不以任何特殊方式解释点。 However, I like to make it explicit - if change '.'
但是,我喜欢明确 - 如果改变'。' for ':' for example, then while it's quoted it will stay with the explicit character, but unquoted it would be "the culture-specific time separator".
例如,对于':',当它被引用时,它将保留显式字符,但不引用它将是“特定于文化的时间分隔符”。 It wasn't entirely obvious to me whether "."
对我来说,“是否”并不完全明显。 would be interpreted as "the culture-specific decimal separator" or not, hence the quoting.
将被解释为“文化特定的小数分隔符”,因此引用。 You may feel that's over the top, of course - it's entirely your decision.
当然,你可能觉得它超过了顶层 - 这完全是你的决定。
You may also want to specify the invariant culture, just to remove any other traces of doubt: 您可能还想指定不变文化,只是为了消除任何其他疑点:
string formatted = dt.ToString("dd'.'MM'.'yyyy", CultureInfo.InvariantCulture);
(At that point the quotes around the dot become less relevant, as "." is the decimal separator in the invariant culture anyway.) (此时点周围的引号变得不那么相关,因为“。”无论如何都是不变文化中的小数分隔符。)
Yes, you can use DateTime.ToString like this: 是的,您可以像这样使用DateTime.ToString:
myDateVariable.ToString("dd.MM.yyyy");
Note that you have to use capital MM here, since mm evaluates to minutes instead of months. 请注意,您必须在此处使用大写MM,因为mm的计算结果为分钟而不是几个月。
Here's an alternative for you: 这是您的另一种选择:
DateTime.Now.ToString("d", new CultureInfo("de-DE"))
German's use .
德国的使用
.
as the date separator. 作为日期分隔符。
You can format the date like this: 您可以格式化日期,如下所示:
date.ToString("dd.MM.yyyy")
When formatting numbers the period .
格式化数字时
.
will change depending on the CultureInfo
used, but not when formatting dates. 将根据使用的
CultureInfo
更改,但在格式化日期时不会更改。
If you are verifying your code against the code analysis rule CA1304: Specify CultureInfo you will have to use the invariant culture even though it doesn't matter for this particular format: 如果要根据代码分析规则CA1304验证代码:指定CultureInfo ,即使对于此特定格式无关紧要,您也必须使用不变文化:
date.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.