到目前为止的字符串 - 在C#["Mon Jan 13 2014 00:00:00 GMT + 0000(GMT标准时间)"]

use*_*418 6 c# datetime date-format

我有一种情况,我以下列格式收到日期作为字符串.

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

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

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

Convert.ToDateTime(SelectedData)    
Run Code Online (Sandbox Code Playgroud)

以上代码出现以下错误:

'Convert.ToDateTime(SelectedData)' threw an exception 
       of type 'System.FormatException' System.DateTime {System.FormatException}
Run Code Online (Sandbox Code Playgroud)

有什么建议?

我无法更改我收到日期最佳问候的格式.

Mik*_*oud 14

您将需要使用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);
Run Code Online (Sandbox Code Playgroud)

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

date.ToString("yyyy-MM-dd");
Run Code Online (Sandbox Code Playgroud)

这是一个证明它的Ideone.

  • 这工作:var date = DateTime.ParseExact(s,“ ddd MMM dd yyyy HH:mm:ss'GMT'K'(GMT标准时间)'”,System.Globalization.CultureInfo.InvariantCulture); // Tx伙计们,此快速帮助 (2认同)

Son*_*nül 7

Convert.ToDateTime使用标准的日期和时间格式,这不是一个标准DateTime格式.

如果你GMT+0000 (GMT Standard Time)的字符串是你的,你可以DateTime.ParseExact改为使用;

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"));
Run Code Online (Sandbox Code Playgroud)

输出将是;

2014-01-13
Run Code Online (Sandbox Code Playgroud)

这里一个demonstration.

欲了解更多信息,请访问: