C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

Examples of how to Calculate Different VB.NET Dates


Posted Date: 20 Apr 2005    Resource Type: Articles    Category: .NET Framework
Author: jitender thakurMember Level: Bronze    
Rating: 1 out of 5Points: 10



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.

Examples of how to Calculate Different VB.NET Dates



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




Responses

Author: lee hopkins    15 Aug 2007Member Level: Bronze   Points : 0
using todays date of 8/15/2007 it is coming back with
mondayofcurrentweek = #8/16/2007 11:04:45 AM#

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

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

End Function


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: How to find out if the computer is connected to Internet ?
Previous Resource: How to start and stop windows services programmatically
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
Related Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use