Parse string date (EEST included) but it fails

泪湿孤枕 提交于 2021-01-29 08:31:14

问题


I am trying to parse a string into a DateTime, but it fails and shows an exception. The code is provided below:

static void Main(string[] args)
{
    string dt = "Wed Sep 05 00:00:00 EEST 2012";
    string Fm = "EEE MMM dd HH:mm:ss zzz yyyy";
    DateTime dateTime;

    dateTime = DateTime.ParseExact(dt, Fm, CultureInfo.InvariantCulture);

    Console.WriteLine(dateTime.Date);
}

This is the exception:

Unhandled Exception: System.FormatException: String was not recognized as a valid DateTime.
   at System.DateTime.ParseExact(String s, String format, IFormatProvider provider)
   at DateParser.Program.Main(String[] args) in C:\Users\AhmedSaeed\source\repos\DateParser\DateParser\Program.cs:line 17

回答1:


DateTime structure does not keep time zone information. It just have date and time values which is based a long called Ticks. That's why there is no custom date and time format string that matches that abbreviation. The zzz format specifier is for the signed offset of the local operating system's time zone from UTC and it is not meaninful to use it with DateTime parsing as stated on the documentation.

If you wanna parse an abbreviation in your string, you have to escape it as a string literal. Other than this, there is no way to parse it. On the other hand, timezone abbreviations are not even unique. For example, CST can mean Central Standard Time, China Standard Time or Cuba Standard Time.

Also there is no EEE custom date format specifier. Abbreviated day names matches with ddd format specifier instead.

string dt = "Wed Sep 05 00:00:00 EEST 2012";
string Fm = "ddd MMM dd HH:mm:ss 'EEST' yyyy";

DateTime dateTime = DateTime.ParseExact(dt, Fm, CultureInfo.InvariantCulture);

Console.WriteLine(dateTime.Date);

Here a demonstration.




回答2:


string dt = "Wed Sep 05 00:00:00 EEST 2012";

Although a real timezone, "EEST" does not match the zzz format (in length) and this may be an issue.

Additionally, as apomene said, EEE is not a valid format string.



来源:https://stackoverflow.com/questions/55283540/parse-string-date-eest-included-but-it-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!