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

StackOverflow https://stackoverflow.com/questions/13126952

質問

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. 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).

Would providing a format provider make any difference? Might it actually produce the wrong results in this case?

役に立ちましたか?

解決 2

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

他のヒント

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.

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. Explain then to your customer that you didn't want to follow the FxCop recommendation.


Best thing would be if .Net included a Xml Culture. Then you could just do

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

For some reason Microsoft choose to create a separate class instead XmlConvert. The class has been there since .Net 1.0.

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

will always create a correct Xml date.

Not sure if it is bug or intended behaviour but XmlConvert.ToString(DateTime.Today, "d") will not create a valid Xml date.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top