获取错误的日期时间格式 [英] Getting Wrong DateTime Format

查看:25
本文介绍了获取错误的日期时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

var dateString = string.Format("{0:dd/MM/yyyy}", date);

但 dateString 是 13.05.2011 而不是 13/05/2011.你能帮我吗?

But dateString is 13.05.2011 instead of 13/05/2011. Can you help me?

推荐答案

您可以将 DateTime.ToStringCultureInfo.InvariantCulture 一起使用:

You could use DateTime.ToString with CultureInfo.InvariantCulture instead:

var dateString = date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

/ 替换为 的原因./ 是自定义格式说明符

The reason why / is replaced with . is that / is a custom format specifier

/"自定义格式说明符代表日期分隔符,用于区分年、月和日.适当的本地化的日期分隔符是从DateTimeFormatInfo.DateSeparator 属性当前或指定的文化.

The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfo.DateSeparator property of the current or specified culture.

因此,要么使用使用 / 作为日期分隔符的 InvariantCulture,或者 - 更合适的 - 通过将其嵌入到 ' 中来转义此格式说明符:

So either use InvariantCulture which uses / as date separator or - more appropriate - escape this format specifier by embedding it within ':

var dateString = date.ToString("dd'/'MM'/'yyyy");

为什么这样更合适?因为您仍然可以应用当地文化,例如如果你想输出月份名称,但你仍然强制 / 作为日期分隔符.

Why this is more appropriate? Because you can still apply the local culture, f.e. if you want to output the month names, but you force / as date separator anyway.

这篇关于获取错误的日期时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆