Date-Time Functions

<<Previous Lesson   <<Table Of Contents>>   Next Lesson>>

There are many useful functions for the date-time operations in VB6. Visual Basic gives you enough power for handling the date and time. Here you’ll learn about those functions in brief.

This post will include the functions that are defined in the DateTime module of the VBA library. Search “DateTime” in Object Browser.



Weekday

The weekday function returns the day of the week. It returns a number representing the day.

Syntax: Variable  =  weekday(Date, [FirstDayOfWeek])


This function takes two arguments, one is the optional. You need to pass a date string to this function, and the first day of week which is optional is set to vbSunday by default.

The constant values of FirstDayOfWeek paramenter are as follows:
vbSunday
vbMonday
vbTuesday
vbWednesday
vbThursday
vbFriday
vbSaturday
vbUseSystemDayOfWeek

Example:
Print Weekday("1/4/2014")

Output: 7



Year

The year function returns the year from the date.

Example:
Print Year("1/4/2014")

Output: 2014




Month

The month function returns the month of the year.

Example:
Dim m As Integer
m = Month("27 / 3 / 2013")
MsgBox m

Output: 3




DateValue

The DateValue function returns the date part from a date/time value.

Example:
Dim dt As Date
dt = DateValue(Now)
Print dt

Output: 1/4/2014




TimeValue

Returns the time part from a date/time value.

Example:
Dim dt As Date
dt = TimeValue(Now)
Print dt

Output: 12:51:25 PM




Day

Returns the day part from a date

Example:
Dt = Day(Now)




Hour

Returns the hour of the day.

Example:
Print Hour(Now)




Minute

Returns the minute of the hour.

Example:
Print Minute(Now)




Second

Returns the second of the minute.

Example:
Print Second(Now)




DatePart

Returns a specific part from a date.

Syntax: DatePart(Interval, Date, [FirstDayOfWeek], [FirstWeekOfYear])


The interval parameter is the interval part of a date you want.
Pass a date value through the Date parameter.
FirstDayOfWeek and FirstWeekOfYear are optional parameters, the values of which are vbSunday and vbFirstJan1

Example:
Print "year = " & DatePart("yyyy", "4/1/2014")
Print "month = " & DatePart("m", Now)
Print "day = " & DatePart("d", Now)
Print "week = " & DatePart("ww", Now)
Print "hour = " & DatePart("h", Now)
Print "minute = " & DatePart("n", Now)
Print "second = " & DatePart("s", Now)
Print "weekday = " & DatePart("y", Now)

The interval values can be:
“yyyy”-Year,
“m”- Month,
 “d”-Day,
“ww”-Week,
“h”-Hour,
“n”-Minute,
“s”-Second,
“y”-weekday.




DateSerial

Returns a Date for a specific year, month and day.

Example:
Print DateSerial(2014, 1, 4)




TimeSerial

Returns a time for a specific hour, minute and second.

Example:
Print TimeSerial(13, 15, 55)




DateDiff

Returns the number of time intervals between two dates.

Example:
dt = DateDiff("d", "5 / 5 / 1990", "26 / 4 / 2013")
The first argument is the interval which can have the value among the interval constants mentioned above.