c# - DateTime and Offset Subtlety -
i'm researching "mechanics" of datetime , related classes in bcl. i'm interested in following odd behavior. consider following code snippet:
var dt1 = new datetime(2014, 10, 24, 15, 30, 00, datetimekind.unspecified); datetimeoffset dto2 = new datetimeoffset(dt1, timespan.fromhours(6)); string input = dto2.tostring("o"); datetime dt6 = datetime.parse(input, cultureinfo.invariantculture, datetimestyles.roundtripkind); console.writeline("dt6:" + dt6.tostring("o")); i know should parse string datetimeoffset, i'm wondering why library allows me here , interesting thing why output be: "dt6:2014-10-24t13:30:00.00000000+04:00" did during parsing set offset actual offset @ given period of time in time zone of local machine , adjusted hours delta between initial offset , resulting one. no matter provide datetimestyles option. kind of resulting value set local, no matter either provide roundtrip value or not. question why sets kind local default , second question datetime stores offset , if stores it, why hell need datetimeoffset class?
a few things:
datetime,datetimeoffsetboth structs, not classes. value types.your question boils down understanding behavior of
datetime.parsemethod - notdatetimestruct. suggest reading the docs method. there lots of bits of information there describe subtlety of behaviors seeing.the docs have return type in "return value" section (emphasis mine):
generally, parse method returns datetime object kind property
datetimekind.unspecified. however, parse method may perform time zone conversion , set value of kind property differently, depending on values ofs,stylesparameters:you're passing value of
"2014-10-24t15:30:00.0000000+06:00"insparameter, contains time zone offset, you're affected first row in chart, , result converted machine's local time zone, whatever may be.the
datetimestyles.roundtripkindflag not going have affect here. you'd see effect if input ended inzinstead of offset, such third row in chart above applied. in case,roundtripkindflag ensuresdatetimekind.utc. without you'd stilldatetimekind.local.the offset not stored. thing stored in
datetimevalue combiningticks,kindproperties 1 64-bit private field.as interesting side note, recognize since 2 bits of field reserved kind, there four possible states, though there 3
datetimekindvalues exposed. indeed, there hidden fourth kind, described under "datetime's deep dark secret" in this article, , in references sources. (basically, it's variation ondatetimekind.local.)if want date/time api makes better sense, consider using noda time.

Comments
Post a Comment