C#:如何将字符串转换为日期时间,其中字符串可以具有任何标准日期时间格式

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

C# : How to convert string to DateTime, where the string can have any of the standard datetime format

c#datetimestring

提问by InfantPro'Aravind'

I had posted a question on DateTime to String conversion, I got many satisfying answers for that .. so I thank StackOverflow very much ..
Here is one more problem of String manupulation, I am stuck with ..

I have to convert a string (from some external source) using C# code .. the string can have these expected format of DateTime ..

我已经发布了一个关于 DateTime 到 String 转换的问题,我得到了很多令人满意的答案 .. 所以我非常感谢 StackOverflow ..
这是字符串操作的另一个问题,我被困在 ..

我必须转换一个字符串(来自某些外部源)使用 C# 代码 .. 字符串可以具有这些预期的 DateTime 格式 ..

  1. 02/31/2009 01:59:59          24 hours format
  2. 02/31/2009 01:59:59 AM    12 hours format
  3. 2/31/2009 1:59:59
  4. 2/31/2009 1:59:59 AM
  5. 02/01/2009 01:59:59 AM
  6. 2/1/2009 1:59:59
  7. and so on .......
  1. 02/31/2009 01:59:59          24小时制
  2. 02/31/2009 01:59:59 AM    12小时制
  3. 2/31/2009 1:59:59
  4. 2/31/2009 1:59:59 AM
  5. 02/01/2009 01:59:59 AM
  6. 2/1/2009 1:59:59
  7. 等等 .......

I tried using DateTime(Convert.ToInt32(string_date.Substring(6,4)),Int,Int,Int,Int,Int,Int)
ie, By extracting the values of month, Day etc

But it doesn't work .. because I can't extract the values with substring perfectly .. as the length of string is Varying
I also have tried to extract the values referring the occurance of "/", "space" and ":" but it becomes bottle neck to derive with (non-)Occurrence of AM/PM

Only the length of Day, Month and Hours can vary ..

我尝试使用DateTime(Convert.ToInt32(string_date.Substring(6,4)),Int,Int,Int,Int,Int,Int)
ie,通过提取月、日等的值

但它不起作用..因为我无法完美地提取带有子字符串的值..因为字符串的长度是 变化的
我也试图提取值指的是“/”、“空格”和“:”的出现,但它变成了(非)AM/PM 出现的瓶颈。

只有日、月和小时的长度可以变化..

采纳答案by Fredrik M?rk

You can use the DateTime.ParseExactoverload that takes a list of formats:

您可以使用DateTime.ParseExact采用格式列表的重载:

private static string[] formats = new string[]
    {
        "MM/dd/yyyy HH:mm:ss tt",
        "MM/dd/yyyy HH:mm:ss",
        "M/dd/yyyy H:mm:ss tt",
        "M/dd/yyyy H:mm:ss"        
    };

private static DateTime ParseDate(string input)
{
    return DateTime.ParseExact(input, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
}

This will throw a FormatExceptionif the passed string does not match any of the given formats. Notice that the formats expecting AM/PM should appear before identical formats without AM/PM ("MM/dd/yyyy HH:mm:ss tt"comes before "MM/dd/yyyy HH:mm:ss").

FormatException如果传递的字符串不匹配任何给定的格式,这将抛出一个。请注意,期望 AM/PM 的格式应该出现在没有 AM/PM 的相同格式"MM/dd/yyyy HH:mm:ss tt"之前(出现在 之前"MM/dd/yyyy HH:mm:ss")。

Update
As Henkpoints out in the comments, the same functionality is available when using TryParseExactwhich removes exception situation. Also, paired with nullable types this can be made a bit cleaner:

更新
正如Henk在评论中指出的那样,使用TryParseExactwhich 删除异常情况时可以使用相同的功能。此外,与可为空类型配对,这可以变得更清晰:

private static DateTime? ParseDate(string input)
{
    DateTime result;
    if (DateTime.TryParseExact(input, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
    {
        return result;
    }
    return null;
}

Now it will simply return a null reference if it fails to parse the input.

现在,如果解析输入失败,它将简单地返回一个空引用。

回答by Darin Dimitrov

Take a look at the TryParseExactmethod. Here's an example with the first case:

看看TryParseExact方法。这是第一种情况的示例:

DateTime date;
// I changed 02/31/2009 to 01/31/2009 because the first is not a valid date
if (DateTime.TryParseExact("01/31/2009 01:59:59", "MM/dd/yyyy HH:mm:ss", null, DateTimeStyles.None, out date))
{
    // string successfully parsed => do something with the date
}

You could then keep a list of different formats and try to parse the string with all of them until you succeed.

然后,您可以保留不同格式的列表,并尝试使用所有格式解析字符串,直到成功为止。

回答by Clover

DateTime dt1 = DateTime.ParseExact("2007/01/01 04:23:12", "yyyy/MM/dd hh:mm:ss", System.Globalization.CultureInfo.CurrentCulture);

DateTime dt1 = DateTime.ParseExact("2007/01/01 04:23:12", "yyyy/MM/dd hh:mm:ss", System.Globalization.CultureInfo.CurrentCulture);

DateTime dt = Convert.ToDateTime("2007/01/01 04:23:12", System.Globalization.CultureInfo.CurrentCulture);

DateTime dt = Convert.ToDateTime("2007/01/01 04:23:12", System.Globalization.CultureInfo.CurrentCulture);

System.Globalization.CultureInfo.CurrentCulture format param

System.Globalization.CultureInfo.CurrentCulture 格式参数

回答by InfantPro'Aravind'

Here are all the possible formats ..

这是所有可能的格式..

  1. MM/dd/yyyy 08/22/2006
  2. dddd, dd MMMM yyyy Tuesday, 22 August 2006
  3. dddd, dd MMMM yyyy HH:mm Tuesday, 22 August 2006 06:30
  4. dddd, dd MMMM yyyy hh:mm tt Tuesday, 22 August 2006 06:30 AM
  5. dddd, dd MMMM yyyy H:mm Tuesday, 22 August 2006 6:30
  6. dddd, dd MMMM yyyy h:mm tt Tuesday, 22 August 2006 6:30 AM
  7. dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
  8. MM/dd/yyyy HH:mm 08/22/2006 06:30
  9. MM/dd/yyyy hh:mm tt 08/22/2006 06:30 AM
  10. MM/dd/yyyy H:mm 08/22/2006 6:30
  11. MM/dd/yyyy HH:mm:ss 08/22/2006 06:30:07
  12. MMMM dd August 22
  13. yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK 2006-08-22T06:30:07.7199222-04:00
  14. ddd, dd MMM yyyy HH':'mm':'ss 'GMT' Tue, 22 Aug 2006 06:30:07 GMT
  15. yyyy'-'MM'-'dd'T'HH':'mm':'ss 2006-08-22T06:30:07
  16. HH:mm 06:30
  17. hh:mm tt 06:30 AM
  18. H:mm 6:30
  19. h:mm tt 6:30 AM
  20. HH:mm:ss 06:30:07
  21. yyyy'-'MM'-'dd HH':'mm':'ss'Z' 2006-08-22 06:30:07Z
  22. dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
  23. yyyy MMMM 2006 August
  1. 月/日/年 2006 年 8 月 22 日
  2. dddd, dd MMMM yyyy 2006 年 8 月 22 日,星期二
  3. dddd, dd MMMM yyyy HH:mm 2006 年 8 月 22 日星期二 06:30
  4. dddd, dd MMMM yyyy hh:mm tt 2006 年 8 月 22 日星期二上午 06:30
  5. dddd, dd MMMM yyyy H:mm 2006 年 8 月 22 日星期二 6:30
  6. dddd, dd MMMM yyyy h:mm tt 2006 年 8 月 22 日星期二上午 6:30
  7. dddd, dd MMMM yyyy HH:mm:ss 2006 年 8 月 22 日星期二 06:30:07
  8. 月/日/年 HH:mm 08/22/2006 06:30
  9. MM/dd/yyyy hh:mm tt 08/22/2006 06:30 AM
  10. 月/日/年 H:mm 08/22/2006 6:30
  11. MM/dd/yyyy HH:mm:ss 08/22/2006 06:30:07
  12. MMMM dd 8 月 22 日
  13. yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK 2006-08-22T06:30:07.7199222-04:00
  14. ddd, dd MMM yyyy HH':'mm':'ss 'GMT' 2006 年 8 月 22 日星期二 06:30:07 GMT
  15. yyyy'-'MM'-'dd'T'HH':'mm':'ss 2006-08-22T06:30:07
  16. 时:分 06:30
  17. 时:分 tt 06:30 AM
  18. 高:毫米 6:30
  19. h:mm tt 上午 6:30
  20. 时:分:秒 06:30:07
  21. yyyy'-'MM'-'dd HH':'mm':'ss'Z' 2006-08-22 06:30:07Z
  22. dddd, dd MMMM yyyy HH:mm:ss 2006 年 8 月 22 日星期二 06:30:07
  23. yyyy MMMM 2006 年 8 月