#82 – Some Common DateTime and TimeSpan Functions

Here are some of the more common operations that you can perform on DateTime objects:

 DateTime dt = new DateTime(1941, 12, 7);
 dt = dt.AddDays(365);      // 7-Dec-1942 12:00AM
 dt = dt.AddYears(4);       // 7-Dec-1946 12:00AM
 dt = dt.AddMinutes(90);    // 7-Dec-1946 1:30AM

 Console.WriteLine(dt.ToShortDateString());   // 12/7/1946
 Console.WriteLine(dt.ToShortTimeString());   // 1:30 AM
 Console.WriteLine(dt.ToLongDateString());    // Saturday, December 07, 1946
 Console.WriteLine(dt.ToLongTimeString());    // 1:30:00 AM

 string[] fms = dt.GetDateTimeFormats();      // 134 different formats, e.g. 12/7/1946, 12/7/46, 1946-12-07, 07-Dec-46, etc.

 DateTime dt2 = DateTime.Parse("1/1/12");     // 1-Jan-2012

And here are some examples of operations that you can perform on TimeSpan objects:

 TimeSpan ts = new TimeSpan(10, 8, 58);       // 10:08:58
 TimeSpan ts2 = new TimeSpan(-11, 0, 0);      // -11 hrs
 ts = ts.Add(ts2);                            // -00:51:02
 TimeSpan ts3 = ts.Duration();        // 00:51:02  (absolute value)

 TimeSpan ts4 = TimeSpan.FromHours(500);      // 20.20:00:00  (20 days, 20 hrs)
 TimeSpan ts5 = TimeSpan.Parse("1:02:03");    // 01:02:03  (1 hr, 2 min, 3 sec)

 TimeSpan ts6 = ts4 + ts5;     // 20.21:02:03
 TimeSpan ts7 = ts4 - ts5;     // 20.18:57:57
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: