使用 C# 将字符串转换为日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1989342/
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-06 22:27:27  来源:igfitidea点击:

Convert string to datetime Using C#

c#asp.netstringdatetime

提问by Ashish

How can i convert String like 20100102 into datetime in a formate of dd/MM/yyyy?

如何将像 20100102 这样的字符串转换为 dd/MM/yyyy 格式的日期时间?

采纳答案by sikender

var userdateformat = DateTime.ParseExact("20101020", "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);

Modify as you want to modify.

随心所欲地修改。

回答by Giorgi

You can use DateTime.ParseExactmethod

您可以使用DateTime.ParseExact方法

回答by Ashish

string strStartDateMain = "20100102";
string strStartDateFinal = new DateTime(Convert.ToInt32strStartDateMain.Substring(0, 4)), Convert.ToInt32(strStartDateMain.Substring(4, 2)), Convert.ToInt32(strStartDateMain.Substring(6))).ToString("dd/MM/yyyy");

回答by JCasso

IFormatProvider culture = new CultureInfo("en-EN", false); // use your culture info
DateTime dt = DateTime.ParseExact(myDateTimeString, "yyyyMMdd", culture, DateTimeStyles.NoCurrentDateDefault); 

yyyyMMdd is input format here.

yyyyMMdd 是这里的输入格式。

And then if you wish convert it to string:

然后,如果您希望将其转换为字符串:

String output = String.Format("{0:dd/MM/yyyy}", dt);

回答by helium

var result = DateTime.ParseExact("20100102", "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);

Modify as needed.

根据需要进行修改。