DateTime.Now.ToString(“MM/DD/YYYY”) contains incorrect month

谁都会走 提交于 2019-12-02 23:06:08

问题


So I have been adding a DateTime.Now.ToString("MM/DD/YYYY") to a List (along with a bunch of other data) and the later writing these lists to individual rows in an Excel workbook.

This all works great (it's something I do regularly), except, the month. I have tried exporting it three times and each time I get a different month; the first time 56/26-17, the second 2/26/2017, and the third 14/26/2017....


回答1:


Use this instead:

DateTime.Now.ToString("MM/dd/yyyy")

"MM" for month. "dd" for days. "yyyy" for year.

"MM/DD/YYYY" is wrong format:

Console.WriteLine(DateTime.Now.ToString("MM/DD/YYYY")) // prints "06/DD/YYYY"



回答2:


DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);

As already answered you need to have format specifier for day and year in small letters but as an add on you should also specify the culture variable to make sure that final output contains "/" between date parts. Without this culture parameter "/" could be replace by the date separator of the culture of system where code is running like "-".



来源:https://stackoverflow.com/questions/44764282/datetime-now-tostringmm-dd-yyyy-contains-incorrect-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!