Skip to main content

Using DateTime in Windows Phone 7


In some instances you find yourself in need of calling a time or date, or even a length of time, but what options do we have? Well, to begin, we have two structures that we can use in conjunction to come up with numerous variations of either or.
First we have the DateTime structure which we can express an instance as a time, date or combination of the two. We also have the option to shorten the format in which we display them with Methods such as “ToShortTimeString” and “ToShortDateString.” We also have the ability to put only certain parts of the DateTime object such as months, days, hours, minutes and such.
We also have yet another tool at our disposal that we can use to put time related data, the TimeSpan structure. We will need to use this hand in hand with our DateTime structure in order to establish a start and end point to the span of time we are trying to encapsulate and manipulate.
Methods such as the DateTime.Subract return values of TimeSpan so there is definitely a need to understand both structures and how they work in unison.
For instance, imagine you are building an application in which you are storing user data but only for a session or a number of days, such as setting up a remind application or calendar, like an organizer.
In our example, once we create a new project, let go ahead and add a Button and TextBlock control. Go and double-click the Button Control to create our OnClick event.
In our Code behind let’s create a new instance of the DateTime object; I will be using an overload that allows me to set the year, month and day. I will be using my Birthday.
Next let’s create an instance of the TimeSpan structure in which we will call “myAge.” We will use this variable to contain the result of the difference of our DateTime object and the DateTIme of the current time. We will be calling the DateTime structure, then calling Subtract, which returns a TimeSpan, and then making a reference to our Birthday instance.
From here let’s go ahead and display this data. To do so we will be setting it to our TextBlock Control; which needs to be of type string. Now we will set the text property of the TextBlock Control equal to our Age instance and calling its ToString Method.
And now you have learned a basic understanding of Date and Time objecting within the Windows Phone 7 operating system. If you have any other questions or concerns and have not yet downloaded the Source Code for this project, I strongly suggest doing so. Seeing it in its entirety can help clear up many of your questions. Thank you for your time and I hope this has been helpful, take care.

Comments