C# 将 dd/MM/yyyy 转换为 MM/dd/YYYY

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12328381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:53:47  来源:igfitidea点击:

Convert dd/MM/yyyy to MM/dd/YYYY

c#date-formattingdate-conversion

提问by Lajja Thaker

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

我需要将“28/08/2012”转换为“08/28/2012”的MM/dd/YYYY格式。
我怎样才能做到这一点?

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

我正在使用下面的代码,但它向我抛出了异常。

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

采纳答案by Nikhil Agrawal

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

您的日期包含/分隔符 ( "28/08/2012") 并且您没有以日期字符串格式 ( "ddMMyyyy")提供该分隔符。

Solution:

解决方案:

It should be "dd/MM/yyyy".

应该是"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.

这样做之后,我们将收到一个 DateTime 对象,其中包含您填充的日期,该对象使用.ToString()所需的日期格式"MM/dd/yyyy"和可选的文化信息传输到字符串CultureInfo.InvariantCulture

回答by Antony Thomas

Since your original date is in en-GBculture, you can create a CultureInfoobject and parse your DateTimenaturally.

由于您的原始日期在en-GB文化中,您可以创建一个CultureInfo对象并DateTime自然地解析您的日期。

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");