Add and subtract functionalities in DateTime and VB.NET

Calculating  DateTime Difference or interval

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


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

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

        Dim TimeDiff As TimeSpan = EndTime - StartTime


        Dim Days As Integer = TimeDiff.Days                 'calculate Value of Days Component

        Dim Minutes As Integer = TimeDiff.Minutes           'calculate Value of Minutes Component

        Dim Seconds As Integer = TimeDiff.Seconds           'calculate Value of Seconds Component

        Dim TotalDays As Integer = TimeDiff.TotalDays       'calculate Value of Total Days

        Dim TotalHours As Integer = TimeDiff.TotalHours     'calculate Value of Total Minutes

        Dim TotalSeconds As Integer = TimeDiff.TotalSeconds 'calculate Value of Total Seconds


        we can use subtrat 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 As Date

            Dim SecondDate As Date


            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)

Similar Articles