如何将诸如2009-05-08 14:40:52,531这样的字符串转换为DateTime?


当前回答

试试这个

DateTime myDate = DateTime.Parse(dateString);

一个更好的方法是:

DateTime myDate;
if (!DateTime.TryParse(dateString, out myDate))
{
    // handle parse failure
}

其他回答

string input;
DateTime db;
Console.WriteLine("Enter Date in this Format(YYYY-MM-DD): ");
input = Console.ReadLine();
db = Convert.ToDateTime(input);

//////// this methods convert string value to datetime
///////// in order to print date

Console.WriteLine("{0}-{1}-{2}",db.Year,db.Month,db.Day);

由于您处理的是基于24小时的时间,并且您使用逗号分隔秒分数,因此我建议您指定一个自定义格式:

DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
                                       System.Globalization.CultureInfo.InvariantCulture);

如果您不确定输入值,也可以如下所示使用DateTime.TryParseExact()。

DateTime outputDateTimeValue;
if (DateTime.TryParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out outputDateTimeValue))
{
    return outputDateTimeValue;
}
else
{
    // Handle the fact that parse did not succeed
}

DateTime。解析

语法:

DateTime.Parse(String value)
DateTime.Parse(String value, IFormatProvider provider)
DateTime.Parse(String value, IFormatProvider provider, DateTypeStyles styles)

例子:

string value = "1 January 2019";
CultureInfo provider = new CultureInfo("en-GB");
DateTime.Parse(value, provider, DateTimeStyles.NoCurrentDateDefault););

值:日期和时间的字符串表示形式。 提供者:提供特定区域性信息的对象。 样式:为某些日期和时间解析方法自定义字符串解析的格式化选项。例如,AllowWhiteSpaces是一个值,它有助于忽略字符串中出现的所有空格。

同样值得记住的是,DateTime是一个在框架内部存储为数字的对象,只有当你将它转换回字符串时,Format才适用于它。

解析:将字符串转换为内部数字类型。 将内部数值转换为可读的格式 字符串。

我最近有一个问题,我试图转换一个日期时间传递给Linq,我当时没有意识到的是格式是不相关的,当传递日期时间到Linq查询。

DateTime SearchDate = DateTime.Parse(searchDate);
applicationsUsages = applicationsUsages.Where(x => DbFunctions.TruncateTime(x.dateApplicationSelected) == SearchDate.Date);

完整的DateTime文档

似乎没有人实现过扩展方法。通过@CMS的回答:

工作和改进的完整源代码示例在这里:Gist Link

namespace ExtensionMethods {
    using System;
    using System.Globalization;

    public static class DateTimeExtensions {
        public static DateTime ToDateTime(this string s, 
                  string format = "ddMMyyyy", string cultureString = "tr-TR") {
            try {
                var r = DateTime.ParseExact(
                    s: s,
                    format: format,
                    provider: CultureInfo.GetCultureInfo(cultureString));
                return r;
            } catch (FormatException) {
                throw;
            } catch (CultureNotFoundException) {
                throw; // Given Culture is not supported culture
            }
        }

        public static DateTime ToDateTime(this string s, 
                    string format, CultureInfo culture) {
            try {
                var r = DateTime.ParseExact(s: s, format: format, 
                                        provider: culture);
                return r;
            } catch (FormatException) {
                throw;
            } catch (CultureNotFoundException) {
                throw; // Given Culture is not supported culture
            }

        }

    }
}

namespace SO {
    using ExtensionMethods;
    using System;
    using System.Globalization;

    class Program {
        static void Main(string[] args) {
            var mydate = "29021996";
            var date = mydate.ToDateTime(format: "ddMMyyyy"); // {29.02.1996 00:00:00}

            mydate = "2016 3";
            date = mydate.ToDateTime("yyyy M"); // {01.03.2016 00:00:00}

            mydate = "2016 12";
            date = mydate.ToDateTime("yyyy d"); // {12.01.2016 00:00:00}

            mydate = "2016/31/05 13:33";
            date = mydate.ToDateTime("yyyy/d/M HH:mm"); // {31.05.2016 13:33:00}

            mydate = "2016/31 Ocak";
            date = mydate.ToDateTime("yyyy/d MMMM"); // {31.01.2016 00:00:00}

            mydate = "2016/31 January";
            date = mydate.ToDateTime("yyyy/d MMMM", cultureString: "en-US"); 
            // {31.01.2016 00:00:00}

            mydate = "11/شعبان/1437";
            date = mydate.ToDateTime(
                culture: CultureInfo.GetCultureInfo("ar-SA"),
                format: "dd/MMMM/yyyy"); 
         // Weird :) I supposed dd/yyyy/MMMM but that did not work !?$^&*

            System.Diagnostics.Debug.Assert(
               date.Equals(new DateTime(year: 2016, month: 5, day: 18)));
        }
    }
}