Date Handling Functions

 

Recall the VB.NET keywords that reference the current date and/or time:

 

            Now                 Returns the current date and time together

            Today               Returns the current date

            TimeOfDay       Returns the current time

 

 

Functions to Isolate Part of a Date

 

For the examples that follow, assume that the current Date/Time (Now) is Friday, August 31, 2001 at 9:15:20 PM.

 

The following functions isolate the date portion and time portion, respectively, of a Date/Time value:

 

Function

Description

DateValue

Returns the date portion of a Date/Time value, with the time portion "zeroed out". (Note: When the time portion of a date/time variable is "zeroed out", the time would be interpreted as 12:00 AM.)

 

Example:

 

Dim dtmTest As Date

dtmTest = DateValue(Now)

 

At this point, the date portion of dtmTest is 8/31/2001, with a time portion of 0 (12:00 AM midnight).

 

Alternatively, the Date property can be used:

dtmTest = Now.Date

 

TimeValue

Returns the time portion of a Date/Time value, with the date portion "zeroed out". (Note: When a date/time variable is "zeroed out", the date will actually be interpreted as January 1, 0001.)

 

Example:

 

Dim dtmTest As Date

dtmTest = TimeValue(Now)

 

At this point, the time portion of dtmTest is 9:15:20 PM, with a date portion of 0 (1/1/0001).

 

Note: There is a TimeOfDay property, however this returns a TimeSpan value, not a DateTime value, so additional manipulation would be required to come up with an equivalent result.

 

 

The following functions are used to isolate a particular part of a date:

 

Function

Description

Weekday

Returns a number from 1 to 7 indicating the day of the week for a given date, where 1 is Sunday and 7 is Saturday.

 

Example:

intDOW = Weekday(Now)         ' intDOW = 6

 

Note:

When necessary to refer to a day of the week in code, VB has a set of built-in constants that can be used instead of the hard-coded values 1 thru 7:

            Constant                                   Value

            DayOfWeek.Sunday                  1

            DayOfWeek.Monday                 2

            DayOfWeek.Tuesday                 3

            DayOfWeek.Wednesday            4

            DayOfWeek.Thursday                5

            DayOfWeek.Friday                    6

            DayOfWeek.Saturday                7

 

Alternatively, the DayOfWeek property can be used:

dtmTest = Now.DayOfweek

 

 

Function

Description

WeekdayName

Returns a string containing the weekday name ("Sunday" thru "Saturday"), given a numeric argument with the value 1 through 7.

 

Example:

strDOW = WeekdayName(6)       ' strDOW = "Friday"

 

The WeekdayName function takes an optional, second argument (Boolean) indicating whether or not to abbreviate the weekday name. By default, the second argument is False, meaning do not abbreviate and return the full name. If True, the first three letters of the weekday name will be returned:

 

Example:

strDOW = WeekdayName(6, True) ' strDOW = "Fri"

 

You can nest the Weekday function within the WeekdayName function to get the weekday name for a given date:

 

Example:

strDOW = WeekdayName(Weekday(Now))  ' strDOW = "Friday"

     

Month

Returns a number from 1 to 12 indicating the month portion of a given date.

 

Example:

intMonth = Month(Now)               ' intMonth = 8

 

Alternatively, the Month property can be used:

dtmTest = Now.Month

 

MonthName

Returns a string containing the month name ("January" thru "December"), given a numeric argument with the value 1 through 12.

 

Example:

strMoName = MonthName(8)            ' strMoName = "August"

 

The MonthName function takes an optional, second argument (Boolean) indicating whether or not to abbreviate the month name. By default, the second argument is False, meaning do not abbreviate and return the full name. If True, the first three letters of the month name will be returned:

 

Example:

strMoName = MonthName(8, True)      ' strMoName = "Aug"

 

You can nest the Month function within the MonthName function to get the month name for a given date:

 

Example:

strMoName = MonthName(Month(Now))   ' strMoName = "August"

 

Day

Returns a number from 1 to 31 indicating the day portion of a given date.

 

Example:

intDay = Day(Now)             ' intDay = 31

 

Alternatively, the Day property can be used:

dtmTest = Now.DayOfweek

 

Year

Returns a number from 100 to 9999 indicating the year portion of a given date.

 

Example:

intYear = Year(Now)                 ' intYear = 2001

 

Alternatively, the Year property can be used:

dtmTest = Now.Year

 

 

The following functions are used to isolate a particular part of a time:

 

Function

Description

Hour

Returns an integer specifying a whole number between 0 and 23 representing the hour of the day.

 

Example:

intHour = Hour(Now)                 ' intHour = 21 (for 9 PM)


Alternatively, the Hour property can be used:

dtmTest = Now.Hour

 

Minute

Returns an integer specifying a whole number between 0 and 59 representing the minute of the hour.

 

Example:

intMinute = Minute(Now)             ' intMinute = 15

 

Alternatively, the Minute property can be used:

dtmTest = Now.Minute

 

Second

Returns an integer specifying a whole number between 0 and 59 representing the second of the minute.

 

Example:

intSecond = Second(Now)             ' intSecond = 20

 

Alternatively, the Second property can be used:

dtmTest = Now.Second

 

 

Additional Properties and Methods of DateTime Values:

In addition to the functions described above (and their equivalent properties, where applicable), .NET introduced a few additional properties and methods of DateTime values:

 

Property

Description

DayOfYear

Returns an integer specifying a whole number between1 and 366 representing the day of the year.

 

Example:

intDOY = Now.DayOfYear

 

If the current date was February 1, the variable intDOY above would contain the value 32.

 

Method

Description

DaysInMonth

Returns an integer specifying the number of days in a specified month and year.

 

Example:

intNumDaysInMo = DateTime.DaysInMonth(2012, 2)

 

The above would return 29 (because 2012 is a leap year).

 

IsLeapYear

Returns a Boolean indicating whether or not a specified year is a leap year.

 

Examples:

If DateTime.IsLeapYear(2012) Then ...  ' returns true

If DateTime.IsLeapYear(2011) Then ...  ' returns false

 

 

 

To demonstrate the date functions shown thus far, create a new "Try It" project, and place the following code in Sub Main:

 

        Console.WriteLine("Now: " & Now)

        Console.WriteLine()

        Console.WriteLine("Using DateValue:             " & DateValue(Now))

        Console.WriteLine("Using TimeValue:             " & TimeValue(Now))

        Console.WriteLine("Using Weekday:               " & Weekday(Now))

        Console.WriteLine("Using WeekdayName:           " & WeekdayName(Weekday(Now)))

        Console.WriteLine("Using WeekdayName (abbrev.): " & WeekdayName(Weekday(Now), True))

        Console.WriteLine("Using Month:                 " & Month(Now))

        Console.WriteLine("Using MonthName:             " & MonthName(Month(Now)))

        Console.WriteLine("Using MonthName (abbrev.):   " & MonthName(Month(Now), True))

        Console.WriteLine("Using Day:                   " & Day(Now))

        Console.WriteLine("Using Year:                  " & Year(Now))

        Console.WriteLine("Using Hour:                  " & Hour(Now))

        Console.WriteLine("Using Minute:                " & Minute(Now))

        Console.WriteLine("Using Second:                " & Second(Now))

        Console.ReadLine()

 

 

Run the project to see the various parts of the current date and time as extracted with the date part functions presented above.

 

 

 

Download the VB project code for the example above here.

 

 

The DatePart Function

 

The generic DatePart function returns an Integer containing the specified part of a given date/time value. Thus, it incorporates the functionality of the Weekday, Month, Day, Year, Hour, Minute, and Second functions. In addition, it can used to get the quarter of a given date (1 through 4), the "Julian" date (the day of the year from 1 to 366), and the week number (1 through 53).

 

Syntax:

DatePart(interval, date[,firstdayofweek[, firstweekofyear]])

 

The DatePart function syntax has these parts:

 

Part

Description

interval

Required. String expression or enumeration value that is the interval of time you want to return. Either the quoted string expression or the enumeration value ("DateInterval.xxxxx") can be used here.

 

The string expression or enumeration value can be any of the following:

 

Expression

Enumeration Value

Description

Possible Range of Values

"yyyy"

DateInterval.Year

Year

100 to 9999

"q"

DateInterval.Quarter

Quarter

1 to 4

"m"

DateInterval.Month

Month

1 to 12

"y"

DateInterval.DayOfYear

Day of year

1 to 366 (a "Julian" date)

"d"

DateInterval.Day

Day

1 to 31

"w"

DateInterval.Weekday

Weekday

1 to 7

"ww"

DateInterval.WeekOfYear

Week

1 to 53

"h"

DateInterval.Hour

Hour

0 to 23

"n"

DateInterval.Minute

Minute

0 to 59

"s"

DateInterval.Second

Second

0 to 59

 

 

 

 

date

Required. Date value that you want to evaluate.

 

firstdayofweek

Optional. A constant that specifies the first day of the week. If not specified, Sunday is assumed.

 

firstweekofyear

Optional. A constant that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs.

 

 

To demonstrate the DatePart function, create a new "Try It" project, and place the following code in Sub Main:

 

        Console.WriteLine("Current date/time is: ")

        Console.WriteLine(Format(Now, "Long Date") & " " & Format(Now, "Long Time"))

        Console.WriteLine()

        Console.WriteLine("*** DatePart Function Examples ***")

        Console.WriteLine("Using DateInterval.Year:       " & DatePart(DateInterval.Year, Now))

        Console.WriteLine("Using DateInterval.Quarter:    " & DatePart(DateInterval.Quarter, Now))

        Console.WriteLine("Using DateInterval.Month:      " & DatePart(DateInterval.Month, Now))

        Console.WriteLine("Using DateInterval.DayOfYear:  " & DatePart(DateInterval.DayOfYear, Now))

        Console.WriteLine("Using DateInterval.Day:        " & DatePart(DateInterval.Day, Now))

        Console.WriteLine("Using DateInterval.Weekday:    " & DatePart(DateInterval.Weekday, Now))

        Console.WriteLine("Using DateInterval.WeekOfYear: " & DatePart(DateInterval.WeekOfYear, Now))

        Console.WriteLine("Using DateInterval.Hour:       " & DatePart(DateInterval.Hour, Now))

        Console.WriteLine("Using DateInterval.Minute:     " & DatePart(DateInterval.Minute, Now))

        Console.WriteLine("Using DateInterval.Second:     " & DatePart(DateInterval.Second, Now))

        Console.ReadLine()

 

Run the project to see the various parts of the current date and time as extracted by the DatePart function.

 

 

Download the VB project code for the example above here.

 

 

 

Piecing Separate Numbers Together to Form a Date or Time Value

 

In the previous examples, we saw ways to isolate parts of a date/time value. What if you need to go the "other way"? If you have the separate parts of a date/time value in different variables and want to piece them together to formulate a date or time, there are two functions you can use to do this: DateSerial and TimeSerial.

 

The DateSerial takes three numeric arguments: year, month, and day respectively. It returns a date based on those values.

Example:

 

Dim intYear    As Integer

Dim intMonth   As Integer

Dim intDay     As Integer

Dim dtmNewDate As Date

 

intYear = 2001

intMonth = 9

intDay = 2

 

dtmNewDate = DateSerial(intYear, intMonth, intDay)   

' returns 9/2/2001

 

The TimeSerial takes three numeric arguments: hour, minute, and second respectively. It returns a time based on those values.

Example:

 

Dim intHour    As Integer

Dim intMinute  As Integer

Dim intSecond  As Integer

Dim dtmNewTime As Date

 

intHour = 11   

intMinute = 34

intSecond = 44

 

dtmNewTime = TimeSerial(intHour, intMinute, intSecond) 

'returns 11:34:44 (AM)

 

Alternatively, you can use New DateTime to populate a DateTime variable using separate parts. The syntax is:      

DateVariable = New DateTime(year, month, day [, hour, minute, second [, millisecond]])

 

The equivalents of the above would be: 

dtmNewDate = New DateTime(intYear, intMonth, intDay)   

dtmNewTime = New DateTime(1, 1, 1, intHour, intMinute, intSecond) 

 

 

The DateAdd Function

 

The DateAdd function enables you to add a specified time interval to a date.

 

Syntax:

DateAdd(interval, number, date)

 

The DateAdd function syntax has these parts:

 

Part

Description

interval

Required. String expression or enumeration value that is the interval of time that you want to add.

 

The string expression or enumeration value can be any of the following:

 

Expression

Enumeration Value

Description

Possible Range of Values

"yyyy"

DateInterval.Year

Year

100 to 9999

"q"

DateInterval.Quarter

Quarter

1 to 4

"m"

DateInterval.Month

Month

1 to 12

"y"

DateInterval.DayOfYear

Day of year

1 to 366 (a "Julian" date)

"d"

DateInterval.Day

Day

1 to 31

"w"

DateInterval.Weekday

Weekday

1 to 7

"ww"

DateInterval.WeekOfYear

Week

1 to 53

"h"

DateInterval.Hour

Hour

0 to 23

"n"

DateInterval.Minute

Minute

0 to 59

"s"

DateInterval.Second

Second

0 to 59

 

Note: To add days to date, you can use either "d", "y", or "w". Be advised that the term "weekday" ("w") has nothing to do with skipping weekend days; i.e., it is NOT equivalent to "business days". Applications that would require skipping weekend days (like Saturday and/or Sunday) would have to be custom coded.

 

number

Required. Numeric expression that is the number of intervals you want to add. It can be positive (to get dates in the future) or negative (to get dates in the past).

 

date

Required. Date value that you want to evaluate.

 

 


To demonstrate the DateAdd function, create a new "Try It" project, and place the following code in Sub Main:

 

        Console.WriteLine("Current date/time is: ")

        Console.WriteLine(Format(Now, "Long Date") & " " & Format(Now, "Long Time"))

        Console.WriteLine()

        Console.WriteLine("*** DateAdd Function Examples (with 3 as the number argument) ***")

        Console.WriteLine("Using DateInterval.Year:       " & DateAdd(DateInterval.Year, 3, Now))

        Console.WriteLine("Using DateInterval.Quarter:    " & DateAdd(DateInterval.Quarter, 3, Now))

        Console.WriteLine("Using DateInterval.Month:      " & DateAdd(DateInterval.Month, 3, Now))

        Console.WriteLine("Using DateInterval.DayOfYear:  " & DateAdd(DateInterval.DayOfYear, 3, Now))

        Console.WriteLine("Using DateInterval.Day:        " & DateAdd(DateInterval.Day, 3, Now))

        Console.WriteLine("Using DateInterval.Weekday:    " & DateAdd(DateInterval.Weekday, 3, Now))

        Console.WriteLine("Using DateInterval.WeekOfYear: " & DateAdd(DateInterval.WeekOfYear, 3, Now))

        Console.WriteLine("Using DateInterval.Hour:       " & DateAdd(DateInterval.Hour, 3, Now))

        Console.WriteLine("Using DateInterval.Minute:     " & DateAdd(DateInterval.Minute, 3, Now))

        Console.WriteLine("Using DateInterval.Second:     " & DateAdd(DateInterval.Second, 3, Now))

        Console.WriteLine()

        Console.WriteLine("*** DateAdd Function Examples (with -3 as the number argument) ***")

        Console.WriteLine("Using DateInterval.Year:       " & DateAdd(DateInterval.Year, -3, Now))

        Console.WriteLine("Using DateInterval.Quarter:    " & DateAdd(DateInterval.Quarter, -3, Now))

        Console.WriteLine("Using DateInterval.Month:      " & DateAdd(DateInterval.Month, -3, Now))

        Console.WriteLine("Using DateInterval.DayOfYear:  " & DateAdd(DateInterval.DayOfYear, -3, Now))

        Console.WriteLine("Using DateInterval.Day:        " & DateAdd(DateInterval.Day, -3, Now))

        Console.WriteLine("Using DateInterval.Weekday:    " & DateAdd(DateInterval.Weekday, -3, Now))

        Console.WriteLine("Using DateInterval.WeekOfYear: " & DateAdd(DateInterval.WeekOfYear, -3, Now))

        Console.WriteLine("Using DateInterval.Hour:       " & DateAdd(DateInterval.Hour, -3, Now))

        Console.WriteLine("Using DateInterval.Minute:     " & DateAdd(DateInterval.Minute, -3, Now))

        Console.WriteLine("Using DateInterval.Second:     " & DateAdd(DateInterval.Second, -3, Now))

        Console.ReadLine()

 

Run the project. You will see two sets of DateAdd results. In the first set, you will see the effect of using 3 as the argument to each of the parts (i.e., current date + 3 years, current date + 3 quarters, current date + 3 days, etc.). In the second set, you will see the effect of using -3 as the argument to each of the parts, effectively "going back in time" – so you will see the current date - 3 years, current date - 3 days, etc.

 

Download the VB project code for the example above here.

 

As an alternative to the DateAdd function, .NET provides the following methods: AddDays, AddMonths, AddYears, AddHours, AddMinutes, and AddSeconds.

For example, Now.AddDays(3) would be equivalent to DateAdd(DateInterval.Day, 3, Now).

 

Adding a Time to a Date

 

We saw previously that you can use the DateValue and TimeValue functions to extract the date portion or time portion, respectively, from a Date field that contains both Date and Time data. What if you need to do the reverse – where you have two separate date fields, one with date data only and one with time data only, and you need to put them together in one date field that contains both date and time data?  Although there is not a specific function to do this, it can be accomplished with the following code (presented in the context of a "Try It" example). Create a new "Try It" project, and place the following code in Sub Main:

 

        Dim dtmDateOnly As Date

        Dim dtmTimeOnly As Date

        Dim dtmBoth As Date

        Console.WriteLine("Current Date/Time is: " & Now)

        Console.WriteLine()

        dtmDateOnly = DateValue(Now) ' isolate date portion

        dtmTimeOnly = TimeValue(Now) ' isolate time portion

        Console.WriteLine()

        Console.WriteLine("dtmDateOnly = " & Format(dtmDateOnly, "M/d/yyyy h:mm:ss tt"))

        Console.WriteLine("dtmTimeOnly = " & Format(dtmTimeOnly, "M/d/yyyy h:mm:ss tt"))

        Console.WriteLine()

        dtmBoth = dtmDateOnly ' initialize the combined variable with the date only var

        Console.WriteLine("    dtmBoth = " & Format(dtmBoth, "M/d/yyyy h:mm:ss tt"))

        dtmBoth = DateAdd(DateInterval.Hour, Hour(dtmTimeOnly), dtmBoth) ' add the hour to the combined variable

        Console.WriteLine("    dtmBoth = " & Format(dtmBoth, "M/d/yyyy h:mm:ss tt"))

        dtmBoth = DateAdd(DateInterval.Minute, Minute(dtmTimeOnly), dtmBoth) ' add the minute to the combined variable

        Console.WriteLine("    dtmBoth = " & Format(dtmBoth, "M/d/yyyy h:mm:ss tt"))

        dtmBoth = DateAdd(DateInterval.Second, Second(dtmTimeOnly), dtmBoth) ' add the seconds to the combined variable

        Console.WriteLine("    dtmBoth = " & Format(dtmBoth, "M/d/yyyy h:mm:ss tt"))

        Console.ReadLine()

 

Run the project. You will see how the resulting variable ("dtmBoth") is built in successive steps. It is first initialized to the desired date (with no time portion), then the desired time is added to it, part by part.

 

Download the VB project code for the example above here.

 

 

The DateDiff Function

 

 

The DateDiff function returns a long integer specifying the number of time intervals between two specified dates.

 

Syntax:

DateDiff(interval, date1, date2[, firstdayofweek[, firstweekofyear]])

 

The DateDiff function syntax has these parts:

 

Part

Description

interval

Required. String expression or enumeration value that is the interval of time you use to calculate the difference between date1 and date2.

 

The string expression or enumeration value can be any of the following:

 

Expression

Enumeration Value

Description

"yyyy"

DateInterval.Year

Year

"q"

DateInterval.Quarter

Quarter

"m"

DateInterval.Month

Month

"y"

DateInterval.DayOfYear

Day of year

"d"

DateInterval.Day

Day

"w"

DateInterval.Weekday

WEEK

"ww"

DateInterval.WeekOfYear

CALENDAR WEEK

"h"

DateInterval.Hour

Hour

"n"

DateInterval.Minute

Minute

"s"

DateInterval.Second

Second

date1, date2

Required; Date. The two dates you want to use in the calculation

 

firstdayofweek

Optional. A constant that specifies the first day of the week. If not specified, Sunday is assumed.

 

firstweekofyear

Optional. A constant that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs.

 

 

 

Remarks

 

You can use the DateDiff function to determine how many specified time intervals exist between two dates. For example, you might use DateDiff to calculate the number of days between two dates, or the number of weeks between today and the end of the year.

 

To calculate the number of days between date1 and date2, you can use either Day of year ("y") or Day ("d"). When interval is Weekday ("w"), DateDiff returns the number of weeks between the two dates. If date1 falls on a Monday, DateDiff counts the number of Mondays until date2. It counts date2 but not date1. If interval is Week ("ww"), however, the DateDiff function returns the number of calendar weeks between the two dates. It counts the number of Sundays between date1 and date2. DateDiff counts date2 if it falls on a Sunday; but it doesn't count date1, even if it does fall on a Sunday.

 

If date1 refers to a later point in time than date2, the DateDiff function returns a negative number.

 

The firstdayofweek argument affects calculations that use the "w" and "ww" interval symbols.

 

If date1 or date2 is a date literal, the specified year becomes a permanent part of that date. However, if date1 or date2 is enclosed in double quotation marks (" "), and you omit the year, the current year is inserted in your code each time the date1 or date2 expression is evaluated. This makes it possible to write code that can be used in different years.

 

When comparing December 31 to January 1 of the immediately succeeding year, DateDiff for Year ("yyyy") returns 1 even though only a day has elapsed.

 


To demonstrate the DateDiff function, create a new "Try It" project, and place the following code in Sub Main:

 

        Console.WriteLine("Current date/time is: ")

        Console.WriteLine(Format(Now, "Long Date") & " " & Format(Now, "Long Time"))

        Console.WriteLine()

        Console.WriteLine("*** DateDiff Function Examples (1/1/2001 vs. Now) ***")

        Console.WriteLine("Using DateInterval.Year:       " & DateDiff(DateInterval.Year, #1/1/2001#, Now))

        Console.WriteLine("Using DateInterval.Quarter:    " & DateDiff(DateInterval.Quarter, #1/1/2001#, Now))

        Console.WriteLine("Using DateInterval.Month:      " & DateDiff(DateInterval.Month, #1/1/2001#, Now))

        Console.WriteLine("Using DateInterval.DayOfYear:  " & DateDiff(DateInterval.DayOfYear, #1/1/2001#, Now))

        Console.WriteLine("Using DateInterval.Day:        " & DateDiff(DateInterval.Day, #1/1/2001#, Now))

        Console.WriteLine("Using DateInterval.Weekday:    " & DateDiff(DateInterval.Weekday, #1/1/2001#, Now))

        Console.WriteLine("Using DateInterval.WeekOfYear: " & DateDiff(DateInterval.WeekOfYear, #1/1/2001#, Now))

        Console.WriteLine("Using DateInterval.Hour:       " & DateDiff(DateInterval.Hour, #1/1/2001#, Now))

        Console.WriteLine("Using DateInterval.Minute:     " & DateDiff(DateInterval.Minute, #1/1/2001#, Now))

        Console.WriteLine("Using DateInterval.Second:     " & DateDiff(DateInterval.Second, #1/1/2001#, Now))

        Console.ReadLine()

 

 

Run the project. You will see the values returned when DateDiff is used to compare the current date to 1/1/2001 using the various intervals.

 

Download the VB project code for the example above here.