c# - How can I parse the following string into DateTime? -


this strange date fromat have never seen before coming api in json.

"tue aug 04 2015 00:17:38 gmt+0000 (utc)"

that generating following error:

system.formatexception: string not recognized valid datetime.

which understandable when using following method parse:

datetime.parse(x.process_date.value) 

anyone dealt complex date formats may know how parse that?

you can use datetime.parseexact method (or datetime.tryparseexact, cleanly handle parsing failures) accomplish this. these methods allow explicitly specify format string.

something work:

var datestring = "tue aug 04 2015 00:17:38 gmt+0000 (utc)"; var format = "ddd mmm dd yyyy hh:mm:ss gmt+0000 (utc)";  var parsed = datetime.parseexact(     datestring,      format,      system.globalization.cultureinfo.invariantculture); 

or, using tryparseexact:

datetime parsed; if (datetime.tryparseexact(    datestring,     format,     system.globalization.cultureinfo.invariantculture,     datetimestyles.none,     out parsed)  {    // parsing successful } else {    // parsing failed } 

here's breakdown of format string used here:

  • ddd - abbreviated name of day of week.
  • mmm - abbreviated name of month.
  • dd - day of month, 01 through 31.
  • yyyy - year four-digit number.
  • hh:mm:ss - hour, using 24-hour clock 00 23; minute, 00 through 59; , second, 0 through 59 (delimited : characters).
  • gmt+0000 (utc) - static text format string assumes present. pretty brittle , cause parsing fail if api ever returns different text here. consider truncating text, or using nodatime offers great support time zones.

you might need tweak format string usage -- example, wasn't clear question whether or not using 12-hour clock or 24-hour clock.

for more information on how build format string, see custom date , time format strings on msdn.

alternatively, eschew using system.datetime in favor of nodatime. i'm less familiar nodatime myself, great documentation available both here on stackoverflow , on nodatime's site.


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -