Wednesday, 15 June 2011

c# - DateTime.TryParse different results -



c# - DateTime.TryParse different results -

as part of unittests application check few datetime strings ability parsed. noticed on 1 machine string "0-02-20 11:36" can parsed {2000-02-20 11:36:00} datetime.tryparse(datestring, out parsedtimestamp) while on other machines can't.

class="lang-cs prettyprint-override">string dt = "0-02-20 11:36"; datetime parsedtimestamp; datetime.tryparse(datestring, out parsedtimestamp); console.writeline(parsedtimestamp);

parsing datetime, parsing in framework, culture dependent.

i assume on exceptional machine, civilization settings utilize yyyy-mm-dd format, while on other machines, date format mm-dd-yyyy.

to work around this, can parse in specific civilization or using invariant culture.

datetime.tryparse(datestring, cultureinfo.invariantculture, datetimestyles.none, out parsedtimestamp);

it turns out there quite few of these cultures:

foreach (var c in cultureinfo.getcultures(culturetypes.allcultures)) { if (c.datetimeformat.shortdatepattern == "yyyy-mm-dd") { console.writeline("{0}: {1}", c.displayname, c.datetimeformat.shortdatepattern); } } korean: yyyy-mm-dd polish: yyyy-mm-dd albanian: yyyy-mm-dd swedish: yyyy-mm-dd khmer: yyyy-mm-dd sinhala: yyyy-mm-dd korean (korea): yyyy-mm-dd polish (poland): yyyy-mm-dd albanian (albania): yyyy-mm-dd swedish (sweden): yyyy-mm-dd central khmer (cambodia): yyyy-mm-dd sinhala (sri lanka): yyyy-mm-dd sami, northern (sweden): yyyy-mm-dd french (canada): yyyy-mm-dd sami, lule (sweden): yyyy-mm-dd sami, southern (sweden): yyyy-mm-dd sami (southern): yyyy-mm-dd sami (lule): yyyy-mm-dd

c# .net datetime string-parsing

No comments:

Post a Comment