【问题标题】:string to date - in C# [ "Mon Jan 13 2014 00:00:00 GMT+0000 (GMT Standard Time)"]迄今为止的字符串 - 在 C# 中 [“2014 年 1 月 13 日星期一 00:00:00 GMT+0000(GMT 标准时间)”]
【发布时间】:2014-01-15 13:35:17
【问题描述】:

我有一种情况,我收到以下格式的字符串形式的日期。

“2014 年 1 月 13 日星期一 00:00:00 GMT+0000(GMT 标准时间)”

我需要在 c# 中将其转换为以下格式(日期/字符串)以进行进一步处理

YYYY-MM-DD (2014-01-13)

Convert.ToDateTime(SelectedData)    

以上代码出现以下错误:

'Convert.ToDateTime(SelectedData)' threw an exception 
       of type 'System.FormatException' System.DateTime {System.FormatException}

有什么建议吗?

我无法更改接收日期的格式 最好的问候。

【问题讨论】:

  • 您是否总是收到完全相同的格式?

标签: c# datetime date-format


【解决方案1】:

你需要使用DateTime.ParseExact:

var date = DateTime.ParseExact(
    "Mon Jan 13 2014 00:00:00 GMT+0000 (GMT Standard Time)",
    "ddd MMM dd yyyy HH:mm:ss 'GMT'K '(GMT Standard Time)'",
    CultureInfo.InvariantCulture);

解析日期后,您可以将其发送出去:

date.ToString("yyyy-MM-dd");

这里有一个Ideone 来证明这一点。

【讨论】:

  • 这有效:var date = DateTime.ParseExact(s, "ddd MMM dd yyyy HH:mm:ss 'GMT'K '(GMT Standard Time)'", System.Globalization.CultureInfo.InvariantCulture ); //Tx 伙计们提供这个快速帮助
  • @user2739418,我已经用您修改的格式编辑了我的答案。很高兴我们能提供帮助!
【解决方案2】:

Convert.ToDateTime 使用标准日期和时间格式,这不是standart DateTime format

如果你的GMT+0000 (GMT Standard Time) 在你的字符串中是默认的,你可以使用DateTime.ParseExact 代替like;

string s = "Mon Jan 13 2014 00:00:00 GMT+0000 (GMT Standard Time)";
var date = DateTime.ParseExact(s,
           "ddd MMM dd yyyy HH:mm:ss 'GMT+0000 (GMT Standard Time)'",
           CultureInfo.InvariantCulture);
Console.WriteLine(date.ToString("yyyy-MM-dd"));

输出将是;

2014-01-13

这里是 demonstration

欲了解更多信息,请查看:

【讨论】:

    【解决方案3】:
    string date = SelectedData.Substring(4, 11);
    string s = DateTime.ParseExact(date, "MMM dd yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
    

    【讨论】:

    • 这对我来说不包括上述所有内容。谢谢@Plue:-*
    猜你喜欢
    • 1970-01-01
    • 2012-02-19
    • 2011-01-30
    • 2020-09-14
    • 1970-01-01
    • 2012-04-27
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多