Convert dd/MM/yyyy to MM/dd/YYYY [duplicate]

*爱你&永不变心* 提交于 2019-12-18 04:08:12

问题


I need to convert "28/08/2012" to MM/dd/YYYY format that means "08/28/2012".
How can I do that?

I am using below code , but it threw exception to me.

DateTime.ParseExact("28/08/2012", "ddMMyyyy",  CultureInfo.InvariantCulture)

回答1:


but it threw exception to me

Problem:

Your date contains / seperator ("28/08/2012") and you are not giving that in your date string format ("ddMMyyyy").

Solution:

It should be "dd/MM/yyyy".

This way

DateTime.ParseExact("28/08/2012", "dd/MM/yyyy", CultureInfo.InvariantCulture)
                        .ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);

After doing that we will receive a DateTime object with your populated dates which is transferred to string using .ToString() with desired date format "MM/dd/yyyy" and optional culture info CultureInfo.InvariantCulture.




回答2:


Since your original date is in en-GB culture, you can create a CultureInfo object and parse your DateTime naturally.

string date = "28/08/2012";
System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
Convert.ToDateTime(date,ci.DateTimeFormat).ToString("d");//short date pattern

(OR)

DateTime.Parse(date,ci.DateTimeFormat).ToString("d");


来源:https://stackoverflow.com/questions/12328381/convert-dd-mm-yyyy-to-mm-dd-yyyy

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