Reputation: 50191
Here are some snippets for a setting I'm working with in C#:
Settings.settings
<Setting Name="SomeSettingUtcDate" Type="System.DateTime" Scope="Application">
<Value Profile="(Default)">10/27/2014 12:00:00</Value>
</Setting>
Settings.Designer.cs
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("11/6/2014 12:00:00")]
public global::System.DateTime SomeSettingUtcDate {
get {
return ((global::System.DateTime)(this["SomeSettingUtcDate"]));
}
}
As you can see by the name, I'd like the date to be in UTC time. And in my use case, the method that accepts a date will check whether the date passed to it is UTC by checking the DateTime.Kind
property and ensuring it is DateTimeKind.Utc
. However, the date returned by calling Settings.Default.SomeSettingUtcDate
will not have this property set.
It seems a hack to create a new DateTime
object with the UTC kind set, in order to satisfy the check in the method being called, because most of the point of using UTC dates is so everyone agrees on when the thing will actually happen, and to prompt people thinking about times and getting it right, the first time. If we take any old date value from the settings file and just assume it is UTC after all, then it seems to me that we may as well NOT check that the Kind
is Utc
, because it doesn't have to be that way in the settings file.
Since my method can be called with another date (not one from the settings file), there is still value in it checking for the UTC kind, so how can I close this gap and make it easier for me and other developers to "fall into the pit of success" with dates stored in settings files?
Is there a way to specify UTC either via a different date time object (so at least the date is presumed to be UTC and visibly displays some indicator of this in the GUI when editing the setting, such as the fact that it's a UtcDateTime for example), or to specify UTC in the date string itself?
Upvotes: 2
Views: 654
Reputation: 292345
The Kind
is not serialized in the settings file, so you can't get it back when you deserialize. The best option is probably to use DateTimeOffset
instead of DateTime
; DateTimeOffset
embeds timezone information, which is included in its string representation, so if you serialize an UTC date, you will get an UTC date when you deserialize.
(note: DateTimeOffset
doesn't appear in the type dropdown list in the settings designer, so you have to select it manually from the "Browse..." entry at the end of the list; it's under mscorlib/System)
Upvotes: 3