rdavin

DateTimePicker Advice - Explicitly specify Kind

Discussion created by rdavin Employee on Oct 10, 2013
Latest reply on Oct 11, 2013 by Mike Zboray

I ran into an issue using the System.Windows.Forms.DateTimePicker control and though I would share my pain.  In recent months my pet peeve seems to revolve around Local vs Utc time.

 

If the user picks (or edits) the control in any way, the resulting DateTime .Value will have .Kind=Unspecified.  In general with my UI’s, I like to present local times to the user so it becomes important for me to later treat the picker’s .Value as local.  If in another instance I presented times as Utc, then it would be equally important to be sure that I later treat those times as Utc.

 

Any of these do NOT work as intended:

 

                var startTime = new AFTime(StartTimePicker.Value);

 

                var startTime = new AFTime(StartTimePicker.Value.ToLocalTime());

 

In the first case, the Unspecified time essentially is treated as Utc by the AFTime constructor, which will introduce an undesired offset.  In the second case, the ToLocalTime() method will introduce the undesired offset before sending the wrong local time to the AFTime constructor (see example at http://msdn.microsoft.com/en-us/library/system.datetime.kind.aspx).

 

 Any of these would work correctly:

 

                var startTime = new AFTime(StartTimePicker.Value.ToString());

 

                var startTime = new AFTime(DateTime.SpecifyKind(StartTimePicker.Value, DateTimeKind.Local));

 

In the first case, strings are treated as local time by the AFTime constructor.  In the second case, we remove any doubt by making well sure the picker’s value will send the correct local time to the AFTime constructor.  The second case is longer but also self-documenting as to what is going on.

 

Switching gears … you may wonder why didn’t I use the AFDateTimePickerCtrl control?  My boss had the same question.   For one, that control isn’t documented so the recommendation from OSIsoft is to not use it (see related link below).  I had more reasons (naturally).  The DateTimePicker has a ValueChanged event and a simple .Value property that returns a DateTime object.  The AFDateTimePickerCtrl requires extra work (or waiting for control to lose focus) to trigger its validation event.  Plus you must grab the Object .EditedObject or else the String .EditedObjectString.  I prefer the simplicity of the DateTimePicker for the properties and events I work with.  All it requires from a developer is a little knowledge that you may want to explicitly declare the Kind when passing the DateTime object to the AFTime constructor.  I know that now, after a wee bit of pain.  Hence this post.

 

Related links:

 

Q: Should I ignore extra AF controls? A: If a control is not documented, the best option is to ignore it.

 

http://vcampus.osisoft.com/discussion_hall/development_with_osisoft_sdks/f/28/p/4339/23101.aspx#23101

Outcomes