【问题标题】:string to date convert C# [duplicate]字符串到日期转换C# [重复]
【发布时间】:2013-09-17 03:28:12
【问题描述】:

我喜欢将字符串“May 01 2000”转换为日期时间

我在下面尝试了这段代码,但出现错误

string date = "May 01 2000";
DateTime DT=Convert.ToDateTime(date)

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:
    string s = "May 01 2000";
    DateTime dt = DateTime.ParseExact(s, "MMM dd yyyy", CultureInfo.InvariantCulture);
    

    但是,您几乎总是最好使用DateTime.TryParse(),因为如果转换失败,它不会引发异常:

    将日期和时间的指定字符串表示形式转换为其 DateTime 等效项,并返回一个 指示是否 转换成功。

    string s = "May 01 2000";
    DateTime dateValue;
    
    if (DateTime.TryParse(s, out dateValue) == true)
    {
        // succeeded ...
    }
    

    【讨论】:

    • 谢谢它解决了我的问题。再次感谢:)
    • 嗨 @mitch 字符串是这样的“Mon May 01 2000 00:00:00 GMT+0800”?
    • 是同一个问题吗?我不确定这是标准格式吗?
    猜你喜欢
    • 2012-02-08
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多