Sunday, 23 February 2014

Date and Time Functions


CDate([expr]): Converts a valid date and time expression to a date variable

Example:
' declare a date variable.
Dim curDate as Date
' set our date variable
curDate = CDate("May 20, 2011")
' curDate contains the date using VB's internal storage formats for date/time.
curDate = CDate("2:45:00 PM")
' curDate now contains the time with today's date.
curDate = CDate("May 20, 2011 2:45:00 PM")
' curDate now contains the date and time specified.

IsDate([expr]): Returns a Boolean value that indicates if the evaulated expression can be converted to a date.

Example:
' declare variables.
Dim myDate as Boolean
' set our date variable
myDate = IsDate("May 20, 2011")
' myDate = True
myDate = IsDate(#05/20/2011#)
' myDate = True
myDate = IsDate("5/20/2011")
' myDate = True
myDate = IsDate("52/20/2011")
' myDate = False
myDate = IsDate("Hello World!")
' myDate = False

FormatDateTime([date], [format]) : Returns date or time in a specified format
[format] can take the following values:
  • 0 = vbGeneralDate - Defualt, Returns date: mm/dd/yy and time if specified: hh:mm:ss am/pm.
  • 1 = vbLongDate - Returns date: weekday, monthname, year
  • 2 = vbShortDate - Returns date: mm/dd/yy
  • 3 = vbLongTime - Returns time: hh:mm:ss am/pm
  • 4 = vbShortTime - Returns time: hh:mm
Some may choose to use the Format() function instead because you can be more specific with the format you want

Now(): Returns the current system date and time

Example:
' declare a date variable.
Dim curDate as Date
' set our date variable
curDate = Now()
' VB will automatically convert from date to string.
MsgBox(curDate)
' Produces a message box with the current date and time.

No comments:

Post a Comment