c# - What is wrong with this DateTime string? -
this string beingness generated application i'm trying debug. datetime.parse works datetime.parseexact doesn't. keeps throwing bad format exception.
// test string datetimeformatted = "2014-11-10t14:49:24-06:00"; seek { //yyyy-mm-ddthh:mm:sszzz 2014-11-10t14:49:24-06:00 datetime mydate = datetime.parseexact(datetimeformatted, "yyyy-mm-ddthh:mm:sszzz", system.globalization.cultureinfo.invariantculture, datetimestyles.none); homecoming mydate; } grab (exception) { seek { // works datetime mydate2 = datetime.parse(datetimeformatted); homecoming mydate2; } grab (exception) { throw; } }
edit:
this final method wrote seems work flawlessly. since method called shortly after application generates timestamp, utilize datetime.now if both datetime.parseexact , datetime.parse fail.
public datetime getdatetimefromformattedstring(string datetimeformatted) { seek { //test info 2014-11-10t14:49:24-06:00 datetime mydate; bool bisparsed = datetime.tryparseexact(datetimeformatted.trim(), "yyyy'-'mm'-'dd't'hh':'mm':'sszzz", system.globalization.cultureinfo.invariantculture, datetimestyles.none, out mydate); if (bisparsed) homecoming mydate; else bisparsed = datetime.tryparse(datetimeformatted.trim(), out mydate); if (bisparsed) homecoming mydate; else homecoming datetime.now; } grab (exception e) { console.writeline(e.stacktrace); homecoming datetime.now; } }
another edit:
this works too
datetimeoffset dto; bool bisparsed = datetimeoffset.tryparseexact(datetimeformatted.trim(), "yyyy-mm-ddthh:mm:sszzz", system.globalization.cultureinfo.invariantculture, datetimestyles.adjusttouniversal, out dto); if (bisparsed) homecoming dto.datetime;
try adding quotes around specific characters in format string:
datetime mydate = datetime.parseexact(datetimeformatted, "yyyy'-'mm'-'dd't'hh':'mm':'sszzz", system.globalization.cultureinfo.invariantculture, datetimestyles.none);
c# string datetime
No comments:
Post a Comment