Monday, April 13, 2009

C# : program to calculate the difference between two give dates and time

i guess this is one of the most important thing a developer must code while developing desktop applications(ie, trial software with time limit).

this is a simple way where one can calculate the differnce between two dates in C#.

program goes as follows.

Calculating the Date Difference using the Subtract Method.




using System;

class Program

{

static void Main(string[] args)

{

System.DateTime somedate =
new System.DateTime(2014, 9, 13, 13, 0, 0);

System.DateTime someotherdate =
new System.DateTime(2006, 9, 13, 0, 0, 0);

System.TimeSpan diffResult =
somedate.Subtract(someotherdate);

Console.WriteLine("difference in days"
+diffResult.Days);

Console.WriteLine("differnce in days
(with decimal precision)" +diffResult.TotalDays);

Console.ReadLine();
}
}





Calculating the Date Difference using the minus symbol('-').


using System;

public class difference TestDateDiff
{

public static void Main()
{

System.DateTime somedate =
new System.DateTime(2014, 9, 13, 0, 0, 0);

System.DateTime someother =
new System.DateTime(2006, 9, 13, 0, 0, 0);

System.TimeSpan diffResult =
somedate - someother;

Console.WriteLine("difference in days = "
+ diffResult.Days);// returns int

Console.WriteLine("difference in days with decimal precision"
+ diffResult.TotalDays);//in decimal fraction

Console.ReadLine();

}

}

No comments:

Post a Comment