简体   繁体   English

将日期转换为具有特定格式的字符串时,是否需要提供IFormatProvider?

[英]Do I need to provide an IFormatProvider when converting a date to a string with a specific format?

If I'm using this: 如果我使用这个:

DateTime.Now.Date.ToString("yyyy-MM-dd")

FXCop complains that I'm violating CA1305 and says that I should provider an IFormatProvider. FXCop抱怨我违反了CA1305,并说我应该提供IFormatProvider。 Do I need to? 我需要吗? I'm asking for the date in a specific format anyway (which is the format I'm expected to put it into the XML as). 无论如何,我都希望以一种特定的格式(该格式是我希望将其放入XML中的格式)来请求日期。

Would providing a format provider make any difference? 提供格式提供者会有所不同吗? Might it actually produce the wrong results in this case? 在这种情况下,它可能会产生错误的结果吗?

Why don't you want to specify the format provider? 您为什么不想指定格式提供者?

If it is just laziness then I can recommend defining two snippets. 如果只是懒惰,那么我建议您定义两个片段。 ic for CultureInfo.InvariantCulture and cc for CultureInfo.CurrentCulture. ic用于CultureInfo.InvariantCulture,而cc用于CultureInfo.CurrentCulture。

Never assume anything about how conversion to string works with the default culture. 对于默认区域性,切勿假设如何转换为字符串。 Not everyone in the world uses the gregorian calendar. 并非世界上每个人都使用公历。 Some day you customer might hire a contractor with a computer with another calendar as default and then you are not generating correct XML. 有一天,您的客户可能会租用一台带有默认默认日历的计算机的承包商,这样您就无法生成正确的XML。 Explain then to your customer that you didn't want to follow the FxCop recommendation. 然后向您的客户说明您不想遵循FxCop的建议。


Best thing would be if .Net included a Xml Culture. 最好的事情是.Net是否包含Xml文化。 Then you could just do 那你就可以做

DateTime.Today.ToString("d", CultureInfo.Xml)  

For some reason Microsoft choose to create a separate class instead XmlConvert . 出于某种原因,Microsoft选择创建单独的类,而不是XmlConvert The class has been there since .Net 1.0. 从.Net 1.0开始,该类就在那里。

XmlConvert.ToString(DateTime.Today, "yyyy-MM-dd")

will always create a correct Xml date. 将始终创建正确的Xml日期。

Not sure if it is bug or intended behaviour but XmlConvert.ToString(DateTime.Today, "d") will not create a valid Xml date. 不确定是错误还是预期的行为,但XmlConvert.ToString(DateTime.Today, "d")不会创建有效的Xml日期。

so after a bit more research it seems that in my instance it doesn't make any difference, but in the general case months might be displayed in a specific locale. 因此,经过更多研究后,看来在我看来这没有什么区别,但是在一般情况下,几个月可能会显示在特定的语言环境中。

More details here: 此处有更多详细信息:

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx http://msdn.microsoft.com/zh-CN/library/8kb3ddd4.aspx

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

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