3
var dateValue = "Mon, 02 May 2016 12:00 PM EDT";
var date = DateTime.ParseExact(
   dateValue,
   "ddd, dd MMM yyyy hh:mm tt K",
   System.Globalization.CultureInfo.InvariantCulture);

As near as I can tell, from the official format string documentation, this should work. Instead, it raises System.FormatException with the rather unhelpful message: String was not recognized as a valid DateTime.

Is there any way to figure out what's going wrong?

Tal Avissar
  • 10,088
  • 6
  • 45
  • 70
Mason Wheeler
  • 82,511
  • 50
  • 270
  • 477
  • 3
    The documentation doesn't mention anything about `K` accepting timezone strings as input, so that is probably your issue. – Sami Kuhmonen May 02 '16 at 17:30
  • @SamiKuhmonen, Find these sentences in the document: `More information: The "K" Custom Format Specifier.` and `The "K" Custom Format Specifier`. There is good description about `K` there. – Siyavash Hamdi May 02 '16 at 17:37

3 Answers3

1

The K Custom Format Specifier does not accept time zone strings.

If you can supply the hour offset instead of a string, then you can use "z".

var dateValue = "Mon, 02 May 2016 12:00 PM -4";
var date = DateTime.ParseExact(
   dateValue,
   "ddd, dd MMM yyyy hh:mm tt z",
   System.Globalization.CultureInfo.InvariantCulture);
Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84
  • I can't supply the hour offset, unfortunately. This timestamp string is coming in as-is from a web service. But I can cut off the timezone string with `.substring()` at least... – Mason Wheeler May 02 '16 at 17:37
  • That's a shame. The link that Sami shared in the comment on your question has something that might help. – Gabriel Luci May 02 '16 at 17:38
0

This should work

var dateValue = "Mon, 02 May 2016 12:00 PM EDT".Replace("EDT", "-4");
var date = DateTime.ParseExact(
dateValue,
"ddd, dd MMM yyyy hh:mm tt z",
System.Globalization.CultureInfo.InvariantCulture);
Mostafiz
  • 7,243
  • 3
  • 28
  • 42
0

https://msdn.microsoft.com/en-us/library/shx7s921%28v=vs.110%29.aspx specifies that the DateTime.Kind enumeration has 3 members. So perhaps it does not like you to specify "EDT" as a kind.

 Member name    Description
 Local          The time represented is local time.
 Unspecified    The time represented is not specified as either local time or Coordinated Universal Time (UTC).
 Utc            The time represented is UTC.
JMG
  • 164
  • 13