C# 如果我的传入日期格式为 YYYYMMDD,则在 .NET 中将字符串转换为日期

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

Convert String to Date in .NET if my incoming date format is in YYYYMMDD

c#.netdatetime

提问by Sreedhar

What is the best way to convert string to date in C# if my incoming date format is in YYYYMMDD

如果我的传入日期格式是在 C# 中将字符串转换为日期的最佳方法是什么 YYYYMMDD

Ex: 20001106

前任: 20001106

采纳答案by Brandon

Use DateTime.ParseExact(). Something like:

使用 DateTime.ParseExact()。就像是:

   string date = "20100102";
   DateTime datetime = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture);

回答by womp

 DateTime.TryParseExact(myDateString, "yyyyMMdd", 
                         CultureInfo.InvariantCulture, 
                         DateTimeStyles.None, out myDateVar )

回答by LukeH

DateTime yourDateTime = DateTime.ParseExact(yourString, "yyyyMMdd", null);

回答by John Knoeller

use DateTime.TryParseExactwith a pattern string of "yyyyMMdd"if you are on .NET 2.0 or better.

如果您使用的是 .NET 2.0 或更高版本,请将DateTime.TryParseExact与模式字符串一起使用"yyyyMMdd"

If you are stuck with .NET 1.1 use DateTime.ParseExact

如果您坚持使用 .NET 1.1,请使用DateTime.ParseExact

see Standard DateTime Format Stringsfor the rules for making pattern strings.

有关创建模式字符串的规则,请参阅标准日期时间格式字符串。

回答by Steve Wortham

Using TryParseExact is generally nicer than ParseExact as it won't throw an exception if the conversion fails. Instead it returns true if it's successful, false if it's not:

使用 TryParseExact 通常比 ParseExact 更好,因为如果转换失败,它不会抛出异常。相反,如果成功则返回 true,否则返回 false:

DateTime dt;
if (DateTime.TryParseExact("20100202", "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
   Console.WriteLine(dt.ToString());
}