tags:

views:

1036

answers:

5

How do I get the date difference in ASP.NET C#?

E.g.: d1= 28/04/2009 09:26:14 d2= 28/04/2009 09:28:14

DateDiff = d2 - d1

+5  A: 

I think you can do it in the following way:

        DateTime d1 = DateTime.Now;
        DateTime d2 = DateTime.Now.AddDays(-1);

        TimeSpan t = d1 - d2;
Cloud
+1  A: 

Check out TimeSpan

Kevin Tighe
+2  A: 
const string DateFormat = "dd/MM/yyyy hh:mm:ss";

DateTime d1 = DateTime.ParseExact("28/04/2009 09:26:14", DateFormat, null);
DateTime d2 = DateTime.ParseExact("28/04/2009 09:28:14", DateFormat, null);

TimeSpan dateDiff = d2 - d1;

string duration = string.Format("The time difference is: {0}", dateDiff);
taoufik
+1  A: 

There is an instance method Subtract on DateTime which returns a TimeSpan. See article

DateTime now = DateTime.Parse("2009-04-28");
DateTime newyear = DateTime.Parse("2009-01-01");
TimeSpan difference = now.Subtract(newyear);

Dries Van Hansewijck
A: 
            Dim d1, d2 As Date
            Dim intElapsedDays As Integer
            Dim tspDif As TimeSpan
            tspDif = d2 - d1
            intElapsedDays = tspDif.Days

´should assign values to d1 and d2

Ricardo Conte