Home > Articles > Computer Software > Business Office Software > Database Software > Other

  • Print
  • + Share This
  • 💬 Discuss

This chapter is from the book

Working with Date Functions

VBA has many functions that help you deal with dates. As long as you understand how Access stores Date/Time values, you should have no problem in working with date functions and values.

→ For a description of the Date/Time datatype see "VBA DataTypes," p. 28.

In this section we go over most of the functions you use when dealing with dates.

Returning the Current Date

To return the current date (as stored on your system) use the following function, which gives you a number counting the days from 12/30/1899:

Date()

How this value is displayed depends on your regional settings. You can use the Date$() function to return a 10-character string representing the date. This string uses the format mm-dd-yyyy. The Date() function returns only the system date; if you need to include the time use the Now() function. As noted earlier, a date/time value is a number where the integer portion represents the date and the decimal portion represents the time. So the Now() function will return an integer and decimal that represents the current date and time. The Now() function defaults to displaying its value according to the regional settings on your PC. On my PC it displays 7/25/2007 5:06:34 PM.

Performing Date Arithmetic

Because dates are stored as numbers, you can do date arithmetic simply by adding or subtracting date values. However, VBA gives you a better way, the DateAdd function. Using this function, you can add 14 days, 14 weeks, 14 months, or 14 years to any date. Or you can find a time 60 hours earlier than the specified date and time.

The following is the syntax for DateAdd, where interval is a string that indicates the type of time period that you want to calculate:

DateAdd(interval, value, date)

Table 4.1 shows the various strings that can be entered as intervals. The number argument is a value or expression that specifies the number of intervals you want to calculate. The number used is an integer. If a decimal value is included, it's rounded to the nearest whole number, before performing the calculation. The date argument is a Date/Time value that is the base value to use in the calculation.

Table 4.1. Interval Settings

String Setting

Description

yyyy

Years

q

Quarters

m

Months

y

Day of year

d

Days

w

Weekdays

ww

Weeks

h

Hours

n

Minutes

s

Seconds

The y, d, and w intervals work interchangeably in the DateAdd function but have more meaning in other Date/Time functions. If the interval evaluates to a negative number, it returns an earlier date/time; a positive number returns a future date/time.

Determining the Difference Between Two Dates

The DateDiff function is used to determine the number of intervals between two date/time values. The following is the syntax for the DateDiff function, where interval is a string that indicates the type of time period used to calculate the difference between the first and second dates represented by date1 and date2 (refer to Table 4.1):

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

Also included in the DateDiff function are two optional arguments: firstdayofweek and firstdayofyear. These are numerical constants that can be used to adjust the first day of a week or year when using the DateDiff function. Tables 4.2 and 4.3 show a list of the values for each constant. The default values are Sunday and January 1, respectively.

Table 4.2. First Day of Week Constants

Constant

Description

Integer Value

vbSunday

Sunday (the default)

1

vbMonday

Monday

2

vbTuesday

Tuesday

3

vbWednesday

Wednesday

4

vbThursday

Thursday

5

vbFriday

Friday

6

vbSaturday

Saturday

7

Table 4.3. First Week of Year Constants

Constant

Description

Integer Value

vbFirstJan1

Use the week in which January 1 occurs (the default).

1

vbFirstFourDays

Use the first week that has at least four days in the new year.

2

vbFirstFullWeek

Use the first full week of the new year.

3

The results from this function might not always be as expected:

  • If date2 falls before date1 , the function yields a negative value.
  • The DateDiff function calculates a year has passed when a new year falls between the two dates, even if there are fewer than 365 days. So when using 12/31 and 1/1 as date1 and date2, respectively, the function returns a 1.

Figure 4.1 shows how these guidelines affect the function in the Immediate window.

Figure 4.1

Figure 4.1 The DateDiff function in action.

Extracting Parts of Dates

The DatePart function is used to extract a portion of a date from a date value. A Date/Time data type contains several components that correspond to the intervals listed in Table 4.1. For example, the following expressions return the values 4, 1, and 2007, respectively:

DatePart("m",#4/1/2007#)

DatePart("d",#4/1/2007#)

DatePart("yyyy",#4/1/2007#)

The DatePart function uses the following syntax, where interval is a String value that defines the part of the date you want to extract and date is a valid Date/Time value (refer to Table 4.1 for a list of interval values):

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

Also included in the DatePart function are two optional arguments: firstdayofweek and firstdayofyear. These are numerical constants that can be used to adjust the first day of a week or year when using the DatePart function. Tables 4.2 and 4.3 show a list of the values for each constant. The default values are Sunday and January 1, respectively.

Creating Dates from the Individual Parts

With DatePart you extract part of a date; conversely, with the DateSerial function you combine the parts of a date to return a date value. The DateSerial function uses the following syntax, where Year, Month, and Day can be any expression that evaluates to an integer value that represents the respective date part:

DateSerial(Year, Month, Day)

There are some rules for each of the arguments:

  • Year is required and must be equal to an integer from 100 to 9999.
  • Month is required, and integers from 1 to 12 (positive or negative) are considered.
  • Day is required, and integers from 0 to 31 (positive or negative) are considered.

The DateSerial function can take integer values outside those ranges and calculate the difference to return a date value. This makes it very powerful if you use expressions for the arguments. For example, the following expression returns June 5, 2008 because the 18th month from the start of 2007 is June:

DateSerial(2007,18,5)

Similarly, the following returns May 15, 2007, by using the 30 days in April and adding the difference of 15 days to the next month:

DateSerial(2007,4,45)

Although this shouldn't be used as a substitute for DateAdd or DateDiff, it can make it easy to create dates from calculated values.

Creating Dates from String Values

The DateValue function can be used to return a date value from a string value; it uses the following syntax, where stringexpression must conform to the formats used by the system's Regional settings:

DateValue(stringexpression)

The following three expressions return the date June 1, 2007:

DateValue("6/1/2007")

DateValue("June 1, 2007")

DateValue("1 Jun 07")

Extracting a Specific Date or Time Portion

Table 4.4 lists several functions that return a specific portion of a date or time value. The syntax for these functions is simple:

Functionname(date/time)

Table 4.4. Date Component Functions

Function

Result

Day(date)

Returns the day of the month as an integer between 1 and 31

Hour(time)

Returns the hour as an integer between 0 and 23

Minute(time)

Returns the minute as an integer between 0 and 59

Second(time)

Returns the second as an integer between 0 and 59

Month(date)

Returns the month as an integer between 1 and 12

Year(date)

Returns the year as an integer between 100 and 9999

A Conversion and Date Example

Sometimes you might need to round a time value to the nearest quarter hour or hour. This example uses some of the conversion and date/time functions previously discussed to accomplish that task.

  1. Create a blank form and put two text boxes on it. Label the boxes txtTime and txtResult.
  2. Add an option group to the form with the options Hour and Quarter Hour. Name the group optType.
  3. Add a button to the form (turn off the wizard first). Name the button cmdRound.
  4. Set the Record Selectors and Navigation buttons to No. Set Scroll Bars to neither.
  5. In the On Click event of the button use the following code:
    Private Sub cmdRound_Click()
    Dim intHrs As Integer, intMin As Integer
    Dim dteTime As Date
    ' convert entered time to Time value
    
    dteTime = CDate(Me.txtTime)
    'extract parts of time
    
    intHrs = DatePart("h", dteTime)
    intMin = DatePart("n", dteTime)
    
    If Me.optType = 1 Then 'test for nearest type
        'Round to nearest hour
        If intMin >= 30 Then
            dteTime = DateAdd("h", 1, dteTime)
            dteTime = DateAdd("n", -intMin, dteTime)
        Else
            dteTime = DateAdd("n", -intMin, dteTime)
        End If
    Else
        'Round to quarter hour
        Select Case intMin
            Case Is < 8
                intMin = 0
            Case 8 To 23
                intMin = 15
            Case 24 To 38
                intMin = 30
            Case 39 To 53
                intMin = 45
            Case Else
                intHrs = intHrs + 1
                intMin = 0
            End Select
        dteTime = TimeSerial(intHrs, intMin, 0)
    End If
    
    'Populate Result control
    Me.txtResult = dteTime
    
    End Sub
    
  6. Save form as frmRound (see Figure 4.2).
    Figure 4.2

    Figure 4.2 The completed frmRound showing an example of input and result.

  • + Share This
  • 🔖 Save To Your Account
Microsoft Office Access 2007 VBA

This chapter is from the book

Microsoft Office Access 2007 VBA

Discussions

comments powered by Disqus