c# - String was not recognized as a valid DateTime on one PC -
language: c#, .net framework: 4.5, method used: datetime.parseexact
so in 1 of our projects we're using following function parse string datetime:
private datetime formatdate(string date, string format) { try { iformatprovider culture = new cultureinfo("en-us", true); datetime dt = datetime.parseexact(date, format, culture); return dt; } catch (exception ex) { throw new exception(ex.message); } }
and calling this:
datetime startdate = formatdate("01/17/2016", "m/d/yyyy");
on our 3 pcs, code works when date format on each pc dd/mm/yyyy, on 2 of pcs, when date format dd-mmm-yy produces bug when trying execute parseexact:
string not recognized valid datetime.
while keeps working on third pc when using dd-mmm-yy format. compared date , time settings on 3 pcs, settings equal, 1 difference on 2 pcs use visual studio 2013 while on third visual studio 2015.
exception details:
message: string not recognized valid datetime.
innerexception: no inner exception
stack: @ system.datetime.parseexact(string s, string format, iformatprovider provider) @ assettracking.popupwindows.additem_warranty.makereminder(trackersdatacontext atdc, items ni, string itemid) in d:\solutions\trackers\trackers\popupwindows\additem_warranty.xaml.cs:line 807 @ trackers.popupwindows.additem_warranty.<>c__displayclass8.b__3() in d:\solutions\tackers\trackers\popupwindows\additem_warranty.xaml.cs:line 685
the question: i'm not sure, different ide part of problem? or else can produce bug on pcs , not on others having exact same date , time settings?
first thing is, exception handling broken:
private datetime formatdate(string date, string format) { try { iformatprovider culture = new cultureinfo("en-us", true); return datetime.parseexact(date, format, culture); } catch (exception ex) { throw new exception(ex.message); } }
there nothing done in catch block, breaks stacktrace. remove all:
private datetime formatdate(string date, string format) { iformatprovider culture = new cultureinfo("en-us", true); return datetime.parseexact(date, format, culture); }
second point is, value provided actually doesn't match pattern dd-mmm-yy
specified. datetime.parseexact
function throws appropriate exception. here's example of valid input value:
var startdate = formatdate("11-mar-16", "dd-mmm-yy");
remove m
if meant month number.
Comments
Post a Comment