Simple operation date and time in C#

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

(1)Comparison of 2 DateTime in size.

DateTime dt1 = Convert.ToDateTime("2010/11/25 20:53:43");
DateTime dt2 = Convert.ToDateTime("2010/11/26 19:24:53");
int i = DateTime.Compare(dt1, dt2);

Finally the results of I is -1... So dt1<dt2.. When dt1=dt2 i=0.. When dt1> DT2 when i=1

(2)Calculation of two DateTime difference.

DateTime dt1 = Convert.ToDateTime("2010/11/25 20:53:43");
DateTime dt2 = Convert.ToDateTime("2010/11/25 20:53:43");
DateTime dt3 = Convert.ToDateTime("2010/11/25 20:53:43");
TimeSpan diff1 = dt2.Subtract(dt1);
DateTime diff2 = dt3.Subtract(dt1);
TimeSpan diff3 = dt2 - dt3;
DateTime diff4 = dt1 - dt2;

Results for the:

  diff1="185.14:47:00";(185 days 14 hours 47 minutes 0 seconds)
  diff2="1996/4/9 17:55:00";
  diff3="55.04:20:00";(55 days 4 hours 20 minutes 0 seconds)
  diff4="1996/4/9 17:55:00";

(3)Calculate a date. Minus or plus a number of days after date

TimeSpan ts = new TimeSpan(40, 0, 0, 0); 
DateTime dt1 = DateTime.Now.Subtract(ts); 
DateTime dt2 = DateTime.Now.Add(ts); 
string str1 = ts.Days.ToString() + "Days ago" + dt1.ToString("Yyyy years MM months DD days"); 
string str2 = ts.Days.ToString() + "Days later" + dt2.ToString("Yyyy years MM months DD days");

Results for the:

  str1="40 days ago in October 16, 2010";
  str2="40 days later in 2011 01 months 04 days";

PS: (calculation date of November 25, 2010)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Estelle at November 17, 2013 - 4:38 AM