In [C#] DateTime Formats, C# Datetime provides verious ways to get the difference between dates. Using C# Datetime we can get difference betwwen two dates, we can get difference between days, difference between hours, difference between Minutes, difference between seconds.
DateTime class provides subtract method to get the difference between two dates.And using System.TimeSpan we can show the difference. We will see C# code that show how to use Subtract method and System.TimeSpan to calculate difference between two dates.
[C#] Example to get difference between two dates:
using System;
namespace DateAndTimeDifferenceSample
{
class Program
{
static void Main(string[] args)
{
DateTime fromdt = new DateTime(2012, 1, 16);
DateTime todt = new DateTime(2012, 2, 17);
TimeSpan dtDiff = todt.Subtract(fromdt);
Console.WriteLine(dtDiff);
}
}
}
//Output wiil show difference in days like below //32.00:00:00
Using C# Datetime we can also get the difference in Hours, Minutes, And Seconds. Let’s see the C# example that show how to calculate difference in Hr, Mins, and in Secs.
Example to get difference for Hours, Minutes, and Seconds [C#]:
class Program
{
static void Main(string[] args)
{
DateTime fromdt = new DateTime(2012, 1, 16, 22, 01, 55);
DateTime todt = new DateTime(2012, 2, 17, 23, 15, 00);
TimeSpan dtDiff = todt.Subtract(fromdt);
Console.WriteLine("Hours" + dtDiff.Hours);
Console.WriteLine("Minutes" + dtDiff.Minutes);
Console.WriteLine("Seconds" + dtDiff.Seconds);
}
}
//OutPut //Hours= 1 //Minutes= 13 //Seconds = 5
0 Comments :
Post a Comment