|
Resources » Articles » .NET Framework
Briefly About System.DateTime Namespace
This article explains how you can play with System.DateTime and System.TimeSpan namespaces
|
Introduction The .Net frame work provides two value types for Date and Time in System namespace They are 1. System.DateTime 2. System.TimeSpan
The DateTime value type has Dates with a range of 10000 years(12:00:00 midnight, January 1, 0001 AD to 11:59:59 P.M., December 31, 9999 A.D.) and a Time with a resolution of 100nano second(Ticks) .
The TimeSpan value represents a period of time and is expressed as a number of ticks(A Tick is 100 nano seconds). What is the relation between DateTime and TimeSpan ? It is very simple the difference between two DateTime values is expressed in a TimeSpan.
DateTime Befor using DateTime you have to create an instance of it, it mainly contains 4 constructors(although total 7 constructors, but 3 are duplicates). The constructors allow you to initialize DateTime structure.
Eg:
DateTime today = new DateTime(2006,5,11,4,15,20);
we can convert DateTime value to string.
string date = today.ToString();
Some common methods of the DateTime structure are: Add, AddDays, AddHours, AddMinutes, AddMonths, AddSeconds, AddYears, DaysInMonth along with the various permuations of the ToString() overload for DateTime
TimeSpan Suppose you date of Birth is 24th October 1983 , 7:15:00 Am now you want to find you age exactly i.e difference between you date of birth and today , how you will get? As we discussed earlier the difference between two dates is TimeSpan , which is the relation between TimeSpan and DateTime.
See the following example , it will give your current age if you give you r date of birth as parameters.
DateTime birthday = new DateTime(1983,10,24,7,15,00); DateTime today = DateTime.Now; TimeSpan age = today - birthday; Label1.Text = age.ToString();
Similarly we can also calculate TimeSpan between two times.
Let us see some examples of how to display dates in various formats using ToString()
DateTime.Now; 5/16/2006 1:05:13 AM DateTime.Now.ToString(); 5/16/2006 1:05:13 AM DateTime.Now.ToShortTimeString() 11:40 AM DateTime.Now.ToShortDateString() 5/16/2006 DateTime.Now.ToLongTimeString() 11:40:13 AM DateTime.Now.ToLongDateString() Tuesday, May 16, 2006
Examples of DateTime for Given Formats
DateTime.Now.ToString("dddd, MMMM dd yyyy") - Tuesday, May 16 2006 DateTime.Now.ToString("ddd, MMM d "'"yy") - Tue, May 16 '06 DateTime.Now.ToString("dddd, MMMM dd") - Tuesday, May 16 DateTime.Now.ToString("M/yy") - 5/06 DateTime.Now.ToString("dd-MM-yy") - 16-05-06
Summary In this article we saw various Formats of Dates in System.DateTime and also learned about TimeSpan
Did you like this resource? Share it with your friends and show your love!
|
|
| Author: nimesh 25 Jul 2009 | Member Level: Bronze Points : 0 | Hello,
It's really nice.
Discribe more.
Thanks -Nimesh
|
|
|