{"id":25,"date":"2012-04-06T17:37:00","date_gmt":"2012-04-06T17:37:00","guid":{"rendered":"https:\/\/blogs.msdn.microsoft.com\/davidrickard\/2012\/04\/06\/datetime-and-datetimeoffset-in-net-good-practices-and-common-pitfalls\/"},"modified":"2021-06-01T06:00:55","modified_gmt":"2021-06-01T06:00:55","slug":"datetime-and-datetimeoffset-in-net-good-practices-and-common-pitfalls","status":"publish","type":"post","link":"https:\/\/engy.us\/blog\/2012\/04\/06\/datetime-and-datetimeoffset-in-net-good-practices-and-common-pitfalls\/","title":{"rendered":"DateTime and DateTimeOffset in .NET: Good practices and common pitfalls"},"content":{"rendered":"<p>It becomes necessary to deal with dates and times in most .NET programs. A lot of programs use DateTime but that structure is frought with potential issues when you start serializing, parsing, comparing\u00a0and displaying dates from\u00a0different time zones and cultures. In this post I will go over these issues and\u00a0the APIs and practices you should use to avoid them.<\/p>\n<p><strong>Background<\/strong><\/p>\n<p>The DateTime structure stores only two pieces of information: Ticks and Kind. 1 tick is 100 nanoseconds (10,000 ticks in a millisecond). The ticks counter represents how many 100ns ticks you are away from 1\/1\/0001 12:00 AM. It&#8217;s the part that determines that it&#8217;s April 6th, 2012, 3:32:07 PM.<\/p>\n<p>Another bit of data is the Kind: represented as a DateTimeKind enumeration. Utc, Local and Unspecified\u00a0are the possible values. Utc means that the ticks counter represents a <a title=\"Coordinated Universal Time\" href=\"http:\/\/en.wikipedia.org\/wiki\/Coordinated_Universal_Time\">Coordinated Universal Time<\/a> (that doesn&#8217;t change due to daylight savings\u00a0or time zones). Local means that it represents the local time of whatever time zone the computer is set to. This one is sensitive to daylight savings. Note that a timezone offset is <em>not<\/em> built in to the DateTime structure. It can only get back to a real UTC time by checking the current time zone settings on the computer. ToUniversalTime() and ToLocalTime() will do these conversions. It will return a new DateTime value with the Ticks adjusted to get the correct year\/month\/day and with the requested type. Calling ToUniversalTime() on a UTC DateTime or ToLocalTime() on a Local DateTime has no effect. Remember that these functions are generating a <em>new<\/em> DateTime value and not modifying the original.<\/p>\n<p>There&#8217;s also\u00a0a third type: Unspecified. This means we don&#8217;t know whether it&#8217;s local or UTC. All we know is the year, month, day, etc. When working with DateTime values, Unspecified is not very helpful since we don&#8217;t know what to do when we want to get a local or UTC time from it. If you call ToUniversalTime() on one of these, it assumes that the type must have been Local and converts based on that. If you call ToLocalTime() it assumes that the type must have been UTC and converts in that direction.<\/p>\n<p>DateTimeOffset is a newer structure. It is also based on ticks but instead of storing a Kind, it keeps track of the offset from UTC as a TimeSpan. A DateTimeOffset always knows what time zone it&#8217;s in. Calling ToUniversalTime() will always result in a TimeSpan.Zero offset, and ToLocalTime() will convert and result in an offset of the user&#8217;s current time zone.<\/p>\n<p><strong>Use DateTimeOffset, not DateTime<\/strong><\/p>\n<p>DateTime has countless traps in it that are likely to give your code bugs:<\/p>\n<ul>\n<li>DateTime values with DateTimeKind.Unspecified are bad news. It&#8217;s common for code\u00a0to call ToUniversalTime() or ToLocalTime() to make sure it&#8217;s got\u00a0the\u00a0date properly ready for storage or display respectively.\u00a0If you call ToUniversalTime() it converts X hours in one direction, but if you call ToLocalTime() on it, it converts X hours in the opposite direction. Both of those can&#8217;t possibly be correct<strong>.<\/strong><\/li>\n<li>DateTime doesn&#8217;t care about UTC\/Local when doing comparisons. <span class=\"selflink\"><span class=\"selflink\"><span class=\"selflink\">It only cares about the number of Ticks on the objects. It could not care less that you&#8217;ve lovingly specified that value A is most certainly UTC and value B is local; it won&#8217;t do any conversions for you. 7:30 AM Local is always going to be evaluated as less than 8:22 AM UTC, even if your timezone is EDT and really the first time was 11:30 AM UTC.<\/span><\/span><\/span><\/li>\n<li><span class=\"selflink\"><span class=\"selflink\"><span class=\"selflink\">DateTime values are not aware of standard format strings. For instance the <span class=\"selflink\"><span class=\"selflink\"><span class=\"selflink\">&#8220;r&#8221; (RFC1123, the format used in HTTP headers) and &#8220;u&#8221; (universal sortable) formats both put UTC markers in the string you serialize to. If you call .ToString(&#8220;u&#8221;) on a local time, DateTime will happily label your local time as UTC without doing any conversion. The basically guarantees disaster when it gets parsed back in again.<\/span><\/span><\/span><\/span><\/span><\/span><\/li>\n<li><span class=\"selflink\"><span class=\"selflink\"><span class=\"selflink\"><span class=\"selflink\"><span class=\"selflink\"><span class=\"selflink\">Parsing a string that has a UTC marker with DateTime does not guarantee a UTC time. <span class=\"selflink\"><span class=\"selflink\"><span class=\"selflink\">If you run DateTime.Parse(&#8220;2012-04-06 23:46:23Z&#8221;) you might expect the result to be a UTC DateTime since the &#8220;Z&#8221; UTC flag is right there in the string, but you do not. It will correctly note that it is dealing with a UTC time, then promptly convert it to a Local time. It&#8217;s still technically correct, but it can result in the hours count changing when you are not expecting it to.<\/span><\/span><\/span><\/span><\/span><\/span><\/span><\/span><\/span><\/li>\n<\/ul>\n<p>But DateTimeOffset doesn&#8217;t have any of these problems! It&#8217;s the newer, more robust version; think of it as DateTime v2. They couldn&#8217;t fix the old DateTime object because that might break existing code that was relying on the bad behavior.<\/p>\n<p>So you&#8217;ll want to use DateTimeOffset in any situation that you&#8217;re referring to a specific point in time. You might still use DateTime for things like general dates (July 4th, 1776) or store hours (9AM-5PM), since they are not affected by time zones.<\/p>\n<p><strong>Pick the right format when serializing<\/strong><\/p>\n<p><span class=\"selflink\"><span class=\"selflink\"><span class=\"selflink\">It&#8217;s common to convert DateTimeOffset values to strings for storage or sending them somewhere else. <\/span><\/span><\/span><span class=\"selflink\"><span class=\"selflink\"><span class=\"selflink\">The <a title=\"list of standard date and time format strings\" href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/az4se3k1.aspx\">list of standard date and time format strings<\/a> is helpful when you are contemplating how to do this.<\/span><\/span><\/span><span class=\"selflink\"><span class=\"selflink\"><span class=\"selflink\"> These are used with the DateTimeOffset.ToString method: for example myDate.ToString(&#8220;u&#8221;). Note how with most of the standard formats you get different\u00a0values for different cultures: different month names, swapped month\/day places, etc. If you use one of these to serialize and Parse back in, it might work if you have the same culture on both sides, but will break if one side uses a different culture. You can get failed parses or swapped month\/day values. Only the &#8220;o&#8221;, &#8220;r&#8221;, &#8220;s&#8221; and &#8220;u&#8221; formats are culture-invariant. Use one of those for serialization:<br \/>\n<\/span><\/span><\/span><\/p>\n<table border=\"0\">\n<tbody>\n<tr>\n<td>Format string<\/td>\n<td>Name<\/td>\n<td>Example<\/td>\n<td><\/td>\n<\/tr>\n<tr>\n<td>&#8220;o&#8221;<\/td>\n<td>Round-trip<\/td>\n<td>2012-04-17T16:46:48.0820143+00:00 <em>(UTC)<\/em><br \/>\n2012-04-17T09:46:48.0820143-07:00 <em>(local)<\/em><\/td>\n<td>The only format that preserves the DateTimeOffset fully. The others round to the nearest second.<\/td>\n<\/tr>\n<tr>\n<td>&#8220;r&#8221;<\/td>\n<td>RFC1123<\/td>\n<td>Tue, 17 Apr 2012 16:46:48 GMT<\/td>\n<td>Used for HTTP headers<\/td>\n<\/tr>\n<tr>\n<td>&#8220;u&#8221;<\/td>\n<td>Universal sortable<\/td>\n<td>2012-04-17 16:46:48Z<\/td>\n<td><\/td>\n<\/tr>\n<tr>\n<td>&#8220;s&#8221;<\/td>\n<td>Sortable<\/td>\n<td>2012-04-17T16:46:48 <em>(UTC)<\/em><br \/>\n2012-04-17T09:46:48 <em>(local)<\/em><\/td>\n<td>Not a great format for this use as it has no timezone or UTC marker and can change based on what offset you have<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><strong><span class=\"selflink\"><span class=\"selflink\"><span class=\"selflink\"><span class=\"selflink\">Conclusion<\/span><\/span><\/span><\/span><\/strong><\/p>\n<p><span class=\"selflink\"><span class=\"selflink\"><span class=\"selflink\"><span class=\"selflink\">Use DateTimeOffset and be careful with serialization. If you&#8217;re dealing with legacy code that&#8217;s using DateTime, be aware of all the timezone-related pitfalls when comparing, serializing, parsing and converting.<br \/>\n<\/span><\/span><\/span><\/span><\/p>\n<p><strong><span class=\"selflink\"><span class=\"selflink\"><span class=\"selflink\"><span class=\"selflink\">One final issue&#8230;<\/span><\/span><\/span><\/span><\/strong><\/p>\n<p><span class=\"selflink\"><span class=\"selflink\"><span class=\"selflink\"><span class=\"selflink\">If it is Coordinated Universal Time, why is the acronym UTC and not CUT? When the English and the French were getting together to work out the notation, the french wanted TUC, for Temps Universel Coordonn\u00e9. UTC was a compromise: it fit equally badly for each language. \ud83d\ude42<\/span><\/span><\/span><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>It becomes necessary to deal with dates and times in most .NET programs. A lot of programs use DateTime but that structure is frought with potential issues when you start serializing, parsing, comparing\u00a0and displaying dates from\u00a0different time zones and cultures. In this post I will go over these issues and\u00a0the APIs and practices you should &hellip; <\/p>\n<p class=\"link-more\"><a href=\"https:\/\/engy.us\/blog\/2012\/04\/06\/datetime-and-datetimeoffset-in-net-good-practices-and-common-pitfalls\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;DateTime and DateTimeOffset in .NET: Good practices and common pitfalls&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false},"categories":[1],"tags":[2,6,8,10],"jetpack_featured_media_url":"","jetpack_publicize_connections":[],"jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/pahBcK-p","jetpack-related-posts":[{"id":51,"url":"https:\/\/engy.us\/blog\/2015\/07\/17\/installing-net-framework-4-5-automatically-with-inno-setup\/","url_meta":{"origin":25,"position":0},"title":"Installing .NET Framework 4.7 automatically with Inno Setup","date":"July 17, 2015","format":false,"excerpt":"In this guide I will walk through how to get the .NET framework to download and install on-the-fly in an Inno Setup installer. It works in 3 steps: Detect if the desired .NET framework is installed Download the .NET Framework bootstrap installer with Inno Download Plugin Run the bootstrap installer\u2026","rel":"","context":"In \".net framework 4.5 inno setup\"","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/engy.us\/blog\/wp-content\/uploads\/2015\/07\/7028.InstallingFramework2-1.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":146,"url":"https:\/\/engy.us\/blog\/2021\/02\/28\/installing-net-5-runtime-automatically-with-inno-setup\/","url_meta":{"origin":25,"position":1},"title":"Installing .NET 5 Runtime Automatically with Inno Setup","date":"February 28, 2021","format":false,"excerpt":"In this guide I will walk through how to get the .NET 5 runtime to download and install on-the-fly in an Inno Setup installer. It works in 3 steps: Detect if the desired .NET runtime is installedDownload the .NET Runtime bootstrap installer with Inno Download PluginRun the bootstrap installer in\u2026","rel":"","context":"With 2 comments","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/engy.us\/blog\/wp-content\/uploads\/2021\/02\/image.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":43,"url":"https:\/\/engy.us\/blog\/2010\/03\/08\/saving-window-size-and-location-in-wpf-and-winforms\/","url_meta":{"origin":25,"position":2},"title":"Saving window size and location in WPF and WinForms","date":"March 8, 2010","format":false,"excerpt":"A common user interface tweak is to save the size and location of a window and restore that state when the program starts up again. That way, the users don\u2019t need to re-do their work of resizing and moving the windows to where they want them. However I\u2019ve found that\u2026","rel":"","context":"With 21 comments","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":156,"url":"https:\/\/engy.us\/blog\/2021\/04\/07\/microsoft-visualstudio-componentmodelhost-dll-issues-in-visual-studio-extensions\/","url_meta":{"origin":25,"position":3},"title":"Microsoft.VisualStudio.ComponentModelHost.dll issues in Visual Studio extensions","date":"April 7, 2021","format":false,"excerpt":"I maintain a Visual Studio extension called Unit Test Boilerplate Generator. Recently I went to release a small fix for it but found that I could no longer build it since reformatting my PC. AppVeyor was also unable to build it after I upgraded it to a VS 2019 build\u2026","rel":"","context":"Similar post","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":120,"url":"https:\/\/engy.us\/blog\/2020\/01\/01\/implementing-a-custom-window-title-bar-in-wpf\/","url_meta":{"origin":25,"position":4},"title":"Implementing a Custom Window Title Bar in WPF","date":"January 1, 2020","format":false,"excerpt":"There are several good reasons for wanting custom window chrome in WPF, such as fitting in additional UI or implementing a Dark theme. However the actual implementation is kind of tricky, since it is now your job to provide a bunch of features that you used to get for free.\u2026","rel":"","context":"With 12 comments","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":159,"url":"https:\/\/engy.us\/blog\/2021\/05\/25\/how-to-use-individual-code-signing-certificates-to-get-rid-of-smartscreen-warnings\/","url_meta":{"origin":25,"position":5},"title":"How to Use Individual Code Signing Certificates to get rid of SmartScreen warnings","date":"May 25, 2021","format":false,"excerpt":"The problem Windows SmartScreen has for a while been trying to keep malware at bay. One of the ways of doing that is putting up a big scary warning when you try to run anything they haven't validated as safe: You have to click \"More info\" then \"Run anyway\" to\u2026","rel":"","context":"With 5 comments","img":{"alt_text":"","src":"https:\/\/i2.wp.com\/engy.us\/blog\/wp-content\/uploads\/2021\/05\/image.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]}],"_links":{"self":[{"href":"https:\/\/engy.us\/blog\/wp-json\/wp\/v2\/posts\/25"}],"collection":[{"href":"https:\/\/engy.us\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/engy.us\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/engy.us\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/engy.us\/blog\/wp-json\/wp\/v2\/comments?post=25"}],"version-history":[{"count":1,"href":"https:\/\/engy.us\/blog\/wp-json\/wp\/v2\/posts\/25\/revisions"}],"predecessor-version":[{"id":162,"href":"https:\/\/engy.us\/blog\/wp-json\/wp\/v2\/posts\/25\/revisions\/162"}],"wp:attachment":[{"href":"https:\/\/engy.us\/blog\/wp-json\/wp\/v2\/media?parent=25"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/engy.us\/blog\/wp-json\/wp\/v2\/categories?post=25"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/engy.us\/blog\/wp-json\/wp\/v2\/tags?post=25"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}