Add and subtract datetime in .Net

Suppose that you have two date time values one is startdate and second is EndDate, and you want to calculate time interval between both dates ,in this situation we can use timespan object like this:

(According to MSDN: A TimeSpan object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date. Otherwise, the DateTime or DateTimeOffset structure should be used instead.) before starting of code

VB.Net

Dim StartTime As DateTime = #6/12/20083:09:00 PM#

Dim EndTime As DateTime = #6/10/200812:04:00 PM#

Dim TimeDiff As TimeSpan = EndTime.Subtract(StartTime)

Dim Days AsInteger= TimeDiff.ToatlDays

'calculate Value of Days Component

Dim Minutes AsInteger= TimeDiff.TotalMinutes

'calculate Value of Minutes Component

Dim Seconds AsInteger= TimeDiff.TotalSeconds

'calculate Value of Seconds Component

Dim TotalDays AsInteger= TimeDiff.TotalDays

'calculate Value of Total Days

Dim TotalHours AsInteger= TimeDiff.TotalHours

'calculate Value of Total Minutes

Dim TotalSeconds AsInteger= TimeDiff.TotalSeconds

'calculate Value of Total Seconds

we can use subtract method for calculating difference between two date like :

TimeDiff = EndTime.Subtract(StartTime)

Add a day, a month and a year to a Date

Dim FirstDate AsDate

Dim SecondDate AsDate

FirstDate = #2/28/2010#

'Add a day

SecondDate = FirstDate.AddDays(1)

'Add some months

SecondDate = FirstDate.AddMonths(6)

'Subtract a year

SecondDate = FirstDate.AddYears(-1)</blockquote>

[C#]

DateTime StartTime =12/06/200815:09:00;

DateTime EndTime =10/06/200812:04:00;

TimeSpan TimeDiff = EndTime.Subtract(StartTime);

int Days = TimeDiff.ToatlDays;

//calculate Value of Days Component

int Minutes = TimeDiff.TotalMinutes;

//calculate Value of Minutes Component

int Seconds = TimeDiff.TotalSeconds;

//calculate Value of Seconds Component

int TotalDays = TimeDiff.TotalDays;

//calculate Value of Total Days

int TotalHours = TimeDiff.TotalHours;

//calculate Value of Total Minutes

int TotalSeconds = TimeDiff.TotalSeconds;

//calculate Value of Total Seconds

//we can use subtract method for calculating difference between two date like :