问题
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