C# 将 dd/mm/yyyy 格式的字符串转换为日期时间

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

Converting dd/mm/yyyy formatted string to Datetime

c#stringdatetime

提问by Fawad Shah

I am new to DotNet and C#. I want to convert a string in mm/dd/yyyyformat to DateTimeobject. I tried the parse function like below but it is throwing a runtime error.

我是 DotNet 和 C# 的新手。我想将mm/dd/yyyy格式的字符串转换为DateTime对象。我尝试了如下所示的 parse 函数,但它引发了运行时错误。

DateTime dt=DateTime.Parse("24/01/2013");

Any ideas on how may I convert it to datetime?

关于如何将其转换为日期时间的任何想法?

采纳答案by Habib

You need to use DateTime.ParseExactwith format "dd/MM/yyyy"

您需要使用DateTime.ParseExact格式"dd/MM/yyyy"

DateTime dt=DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);

Its safer if you use d/M/yyyyfor the format, since that will handle both single digit and double digits day/month. But that really depends if you are expecting single/double digit values.

如果您使用d/M/yyyy该格式,它会更安全,因为它可以处理个位数和两位数的日/月。但这实际上取决于您是否期望单位/两位数字值。



Your date format day/Month/Yearmight be an acceptable date format for some cultures. For example for Canadian Culture en-CADateTime.Parsewould work like:

day/Month/Year对于某些文化,您的日期格式可能是可接受的日期格式。例如,加拿大文化的en-CADateTime.Parse工作方式如下:

DateTime dt = DateTime.Parse("24/01/2013", new CultureInfo("en-CA"));

Or

或者

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
DateTime dt = DateTime.Parse("24/01/2013"); //uses the current Thread's culture

Both the above lines would work because the the string's format is acceptable for en-CAculture. Since you are not supplying any culture to your DateTime.Parsecall, your current culture is used for parsing which doesn't support the date format. Read more about it at DateTime.Parse.

上面两行都可以使用,因为字符串的格式对于en-CA文化来说是可以接受的。由于您没有为您的DateTime.Parse呼叫提供任何文化,因此您当前的文化用于不支持日期格式的解析。在DateTime.Parse阅读更多关于它的信息。



Another method for parsing is using DateTime.TryParseExact

另一种解析方法是使用 DateTime.TryParseExact

DateTime dt;
if (DateTime.TryParseExact("24/01/2013", 
                            "d/M/yyyy", 
                            CultureInfo.InvariantCulture, 
                            DateTimeStyles.None,
    out dt))
{
    //valid date
}
else
{
    //invalid date
}

The TryParsegroup of methods in .Net framework doesn't throw exception on invalid values, instead they return a boolvalue indicating success or failure in parsing.

TryParse组的.NET Framework中的方法不会对无效值,抛出异常,相反,他们返回bool表明解析成功或失败的价值。

Noticethat I have used single dand Mfor day and month respectively. Single dand Mworks for both single/double digits day and month. So for the format d/M/yyyyvalid values could be:

请注意,我分别使用 singledMfor day 和 month 。单数dM适用于单/双位数的日和月。因此,对于格式,d/M/yyyy有效值可能是:

  • "24/01/2013"
  • "24/1/2013"
  • "4/12/2013" //4 December 2013
  • "04/12/2013"
  • “24/01/2013”
  • “24/1/2013”
  • "4/12/2013" //2013 年 12 月 4 日
  • “04/12/2013”

For further reading you should see: Custom Date and Time Format Strings

如需进一步阅读,您应该看到:自定义日期和时间格式字符串

回答by John Woo

use DateTime.ParseExact

DateTime.ParseExact

string strDate = "24/01/2013";
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", null)

nullwill use the current culture, which is somewhat dangerous. Try to supply a specific culture

null将使用当前的文化,这有点危险。尝试提供特定的文化

DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", CultureInfo.InvariantCulture)

回答by Soner G?nül

You can use "dd/MM/yyyy"format for using it in DateTime.ParseExact.

您可以使用"dd/MM/yyyy"格式在DateTime.ParseExact.

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

使用指定的格式和特定​​于区域性的格式信息将日期和时间的指定字符串表示形式转换为其等效的 DateTime。字符串表示的格式必须与指定的格式完全匹配。

DateTime date = DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);

Here is a DEMO.

这是一个DEMO.

For more informations, check out Custom Date and Time Format Strings

欲了解更多信息,请查看 Custom Date and Time Format Strings