Amaan
Amaan

Reputation:

Date Difference in ASP.Net

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

Upvotes: 4

Views: 11369

Answers (6)

Dries Van Hansewijck
Dries Van Hansewijck

Reputation: 1454

There is an instance method Subtract on DateTime class 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);

Upvotes: 3

pyrocumulus
pyrocumulus

Reputation: 9290

I think you can do it in the following way:

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

TimeSpan t = d1 - d2;

Upvotes: 11

hatewise
hatewise

Reputation: 1

It depends on the input format timestamp. If it is, for example, unix timestamp that the code below will enumerate period info:

        int TimestampFrom = 1546336800; //2019.1.1 10:00
        int TimestampTo = 1547555400;   //2019.1.15 12:30
        DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
        long dateFromunixTimeStampInTicks = (long)(TimestampFrom * TimeSpan.TicksPerSecond);
        DateTime dateFrom = new DateTime(unixStart.Ticks + dateFromunixTimeStampInTicks, System.DateTimeKind.Utc);
        long dateTounixTimeStampInTicks = (long)(TimestampTo * TimeSpan.TicksPerSecond);
        DateTime dateTo = new DateTime(unixStart.Ticks + dateTounixTimeStampInTicks, System.DateTimeKind.Utc);
        TimeSpan Period = dateTo - dateFrom;
        int days = Convert.ToInt32(Period.TotalDays);       //>14
        int hours = Convert.ToInt32(Period.TotalHours);     //>338
        int seconds = Convert.ToInt32(Period.TotalSeconds); //>1218600

If source date format is normal DateTime then enough simple subtraction of dates will return TimeSpan structure that contain all period info.

Answering on: "How To get Interval Between Two Datetime (Timestamp) [duplicate]" This is not a duplicate.

Upvotes: 0

Ricardo Conte
Ricardo Conte

Reputation: 151

            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

Upvotes: 1

tofi9
tofi9

Reputation: 5853

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);

Upvotes: 4

Kevin Tighe
Kevin Tighe

Reputation: 21171

Check out TimeSpan

Upvotes: 2

Related Questions