Adding and subtracting date/time values in VB.NET

Started by dhilipkumar, Nov 26, 2008, 08:34 PM

Previous topic - Next topic

dhilipkumar



While it has become common practice for developers to manipulate VB.NET date/time values manually, it's never a good idea because the result is rarely a correct date/time value. Whenever you try to use your own calculation routines for adding and subtracting date/time values, you risk generating a bug since it's hard to check the code for all possible outcomes, whereas utilizing appropriate .NET objects and methods is sure to provide correct results.

As you can see here

Private Sub AddDateTime()


        Dim dtNow As Date = Now()
        MsgBox(dtNow)


        dtNow = dtNow.AddYears(20)
        MsgBox(dtNow) the Date object provides for simple manipulation that allows you to add and subtract date/time values in VB.NET.


        dtNow = dtNow.AddMonths(10)
        MsgBox(dtNow)


        dtNow = dtNow.AddDays(3)
        MsgBox(dtNow)


        dtNow = dtNow.AddHours(5)
        MsgBox(dtNow)


        dtNow = dtNow.AddMinutes(2)
        MsgBox(dtNow)


        dtNow = dtNow.AddSeconds(6)
        MsgBox(dtNow)


        dtNow = dtNow.AddMilliseconds(4)
        MsgBox(dtNow)


        dtNow = dtNow.AddYears(-2)
        MsgBox(dtNow)


    End Sub


the Date object provides for simple manipulation, which allows you to add and subtract date/time values in VB.NET. In the example, I define the Date variable dtNow and set it to the current date/time value. I utilize these Date object methods to manipulate the date: AddYears, AddMonths, AddDays, AddHours, AddMinutes, AddSeconds, and AddMilliseconds. For each method, I specify the number of years or months or hours to add. Subtraction is done by passing a negative value to the method. Notice that these methods will never result in an impossible date; manual manipulation cannot guarantee such results.

dhilipkumar

Examples of how to Calculate Different VB.NET Dates

In this article, I will be showing how to use just the DATEADD and DATEDIFF function to calculate a number of different dates you might need to use in your applications.

Sometime we have to deal with real time application which is system time based and they have to fire at some special occasion or what we call as scheduled task( Our operating system provides scheduled task but they cannot be customized as we desire) . For instance, you might have an application that needs to determine what date is the first day of the month, or need to know the last day of the month. Now most of you probably already know how to separate the date into its piece (year, month, day, etc.) and use those pieces along with a number of functions to calculate a date that you might need. In this article, I will be showing how to use just the DATEADD and DATEDIFF function to calculate a number of different dates you might need to use in your applications.

In order to understand these examples, let's first review the DATEDIFF and DATEADD functions. The DATEDIFF function calculates the amount of time between two dates, where the time part is based on an interval of time, such as hours, days, weeks, months, years, etc. The DATEADD function calculates a date by taking an interval of time, and adding it to a date, where the interval of time will be the same as those used by the DATEDIFF function. To find out more about the DATEDIFF and DATEADD functions and the different intervals of time read Microsoft Books Online.

Public Overloads Function DateDiff( _
ByVal Interval As DateInterval, _
ByVal Date1 As DateTime, _
ByVal Date2 As DateTime, _
Optional ByVal DayOfWeek As FirstDayOfWeek = FirstDayOfWeek.Sunday, _
Optional ByVal WeekOfYear As FirstWeekOfYear = FirstWeekOfYear.Jan1 _
) As Long
Public Overloads Function DateADateInterval.day ( _ ByVal Interval As DateInterval, _
ByVal Number As Double, _
ByVal DateValue As DateTime _
) As DateTime

Enumeration value String Unit of time difference

DateInterval.Day d Day
DateInterval.DayOfYear y Day
DateInterval.Hour h Hour
DateInterval.Minute n Minute
DateInterval.Month, m Month
DateInterval.Quarter q Quarter
DateInterval.Second s Second
DateInterval.Weekday w Week
DateInterval.WeekOfYear ww Calendar week
DateInterval.Year DateInterval.YearDateInterval.Year Year
Public Overloads Function DateADateInterval.day ( _
ByVal Interval As DateInterval, _
ByVal Number As Double, _
ByVal DateValue As DateTime _
) As DateTime

Using the DATEADD and DATEDIFF functions to calculated dates requires you to think a little differently about what it takes to convert the current date into a date you need. You must think in terDateInterval.Second of date intervals. Such as, how many date intervals it is from the current date to the date you want to calculate. Or how many date intervals is it from today to some other date like '1900-01-01', and so on. Understanding how to look at date intervals will help you more easily understand my different date examples.

First Day of Month


For the first example, let me show you how to get the first day of the month from the current date. Remember now, this example and all the other examples in this article will only be using the DATEADD and DATEDIFF functions to calculate our desired date. Each example will do this by calculating date intervals from the current date, and then adding or subtracting intervals to arrive at the desired calculated date. Here is the code to calculate the first day of the month:

Dim firstdate as date=DATEADD(DateInterval.Month, DATEDIFF(DateInterval.Month,,Date.MinValue,today()),Date.MinValue)

Let me review how this works, by breaking this statement apart. The inner most function call "today()", as most of you probably already know, returns the current date and time. Now the next executed function call "DATEDIFF(DateInterval.Month,,,today())" calculates the number of months between the current date and the date "1900-01-01 00:00:00.000". Remember date and time variables are stored as the number of seconds since "1900-01-01 00:00:00.000"; this is why you can specify the first datetime expression of the DATEDIFF function as "0." Now the last function call, DATEADD, add s the number of months between the current date and '1900-01-01". By adding the number of months between our pre-determined date '1900-01-01' and the current date, I am able to arrive at the first day of the current month. In add ition, the time portion of the calculated date will be "00:00:00.000."
The technique shown here for calculating a date interval between the current date and the year "1900-01-01," and then adding the calculated number of interval to "1900-01-01," to calculate a specific date, can be used to calculate many different dates. The next four examples use this same technique to generate different dates based on the current date.

Monday of the Current Week


Here I use the week interval (DateInterval.Weekday) to calculate what date is Monday of the current week. This example assumes Sunday is the first day of the week.

select DATEADD(DateInterval.Weekday, DATEDIFF

(DateInterval.Weekday,Date.MinValue,now()),Date.MinValue)
If you don't want Sunday to be the first day of the week, then you will need to use a different method. This example sets Monday as the first day of the week, but by changing the DATEFIRST setting any day of the week could be the first day of the week.

Public Overloads Function DatePart( _
ByVal Interval As DateInterval, _
ByVal DateValue As DateTime, _
Optional ByVal FirstDayOfWeekValue As FirstDayOfWeek = VbSunday, _
Optional ByVal FirstWeekOfYearValue As FirstWeekOfYear = VbFirstJan1 _
) As Integer

Dim mondayofcurrentweek As Date = DateAdd(DateInterval.Day, 1 - DatePart(DateInterval.Weekday, Now(), vbMonday), Now())

First Day of the Year

Now I use the year interval (DateInterval.Year) to display the first day of the year.

DATEADD(DateInterval.Year, DATEDIFF(DateInterval.Year,Date.MinValue,today()),Date.MinValue)

First Day of the Quarter

If you need to calculate the first day of the current quarter then here is an example of how to do that.

Dim First_Day_of_the_Quarter as date=
DATEADD(DateInterval.Quarter, DATEDIFF(DateInterval.Quarter,Date.MinValue,today()),Date.MinValue)

Midnight for the Current Day

Ever need to truncate the time portion for the datetime value returned from the today() function, so it reflects the current date at midnight? If so then here is an example that uses the DATEADD and DATEDIFF functions to get the midnight timestamp.

Dim Midnight_for_the_CurrentDay as datetime =
DATEADD(DateInterval.day , DATEDIFF(DateInterval.day ,Date.MinValue,today()),Date.MinValue)

Expanding on the DATEADD and DATEDIFF Calculation

As you can see, by using this simple DATEADD and DATEDIFF calculation you can come up with many different dates that might be valuable.

Last Day of Prior Month


Here is an example that calculates the last day of the prior month. It does this by subtracting 3 seconds from the first day of the month example. Now remember the time portion in VB.NET is only accurate to 1 seconds. This is why I needed to subtract 3 seconds to arrive at my desired date and time.

Dim LastDayofPriorMonth

as date= DateAdd(DateInterval.Second, -1, DateAdd(DateInterval.Year, DateDiff(DateInterval.Year, Date.MinValue, Now()),Date.MinValue))
The time portion of the calculated date contains a time that reflects the last millisecond of the day ("23:59:59.997") that VB.NETcan store.

Last Day of Prior Year


Like the prior example to get the last date of the prior year you need to subtract 3 seconds from the first day of year.
Dim Midnight_for_the_Current as date = DateAdd(DateInterval.Second, -3, DateAdd(DateInterval.Year, DateDiff(DateInterval.Year, Date.MinValue, Now()), Date.MinValue))

Last Day of Current Month


Now to get the last day of the current month I need to modify slightly the query that returns the last day of the prior month. The modification needs to add one to the number of intervals return by DATEDIFF when comparing the current date with "1900-01-01." By adding 1 month, I am calculating the first day of next month and then subtraction 3 seconds, which allows me to arrive at the last day of the current month. Here is the TSQL to calculate the last day of the current month.

Dim LastDayofCurrentMonth As Date = DateAdd(DateInterval.Second, -3, DateAdd(DateInterval.Month, DateDiff(m, Date.MinValue, Today()) + 1, Date.MinValue))

Last Day of Current Year


You should be getting the hang of this by now. Here is the code to calculate the last day of the current year.
Dim LastDayofCurrentYear as date
=
DateAdd(DateInterval.Second, -3, DateAdd(DateInterval.Year, DateDiff(DateInterval.Year, Date.MinValue, Today()) + 1, Date.MinValue))

First Monday of the Month


Ok, I am down to my last example. Here I am going to calculate the first Monday of the current month. Here is the code for that calculation.
Dim FirstMondayoftheMonth As Date = DateAdd(DateInterval.Weekday, DateDiff(DateInterval.Weekday, Date.MinValue, DateAdd(DateInterval.Day, 6 - DatePart(DateInterval.Day, Today()), Today())), Date.MinValue)
In this example, I took the code for "Monday of the Current Week," and modified it slightly. The modification was to change the "today()" portion of the code to calculate the 6th day of the current month. Using the 6th day of the month instead of the current date in the formula allows this calculation to return the first Monday of the current month.

Conclusion


I hope that these examples have given you some ideas on how to use the DATEADD and DATEDIFF functions to calculate dates. When using this date interval math method of calculating dates I have found it valuable to have a calendar available to visualize the intervals between two different dates or you have to change system date to access its functionality that is present in task bar click on the time that is displayed on your machine/system. Remember this is only one way to accomplish these date calculations

I hope that these examples have given you some ideas on how to use the DATEADD and DATEDIFF functions to calculate dates. When using this date interval math method of calculating dates I have found it valuable to have a calendar available to visualize the intervals between two different dates or you have to change system date to access its functionality that is present in task bar click on the time that is displayed on your machine/system. Remember this is only one way to accomplish these date calculations

dhilipkumar

You can use the AddDays() method to add or subtract days from the datetime object. To subtract days, just add a negative number.

Similarly, you can use methods like AddHours(), AddMinutes() etc. See the following example :


string formattedDate;

// Calculating the yesterday's date (substracting days from current
date.)
DateTime yesterday = DateTime.Today.AddDays( -1 );
formattedDate = yesterday.ToString("dd / MM / yy");

// Calculating the tomorrow's date (adding days to the current date.)
DateTime tomorrow = DateTime.Today.AddDays( 1 );
formattedDate = tomorrow.ToString("dd / MM / yy");

// Calculating the time after 5 minute (adding minutes to the current
time.)
// Format : 07 / 03 / 04, 10 : 30
DateTime later = DateTime.Now.AddMinutes( 5 );
formattedDate = later.ToString("dd / MM / yy, hh : mm ");



dhoni

from this easy program of .net we can easily add ND SUBTRACT DATE/TIME VALUE IN THIS
this easily use in this program
the program definitely easy to recover on .net

casnova

Thanks, in advance, for any info.
very interesting. thanks for sharing.  :yes   :yes   :yes
โปรโมชั่นสุดแรง สมัครสมาชิกใหม่ วันนี้รับโบนัสฟรีทันที 10% และรับอีก 5% สมัคร royal1688

Sudhakar