DatePart Function |
Microsoft.VisualBasic.DateAndTime
DatePart( interval , datevalue [, firstdayofweekvalue [, _ firstweekofyearvalue ]])
A String literal (see the second item in Section ) or a constant of the DateInterval enum (see the third item in Section ) that defines the part of the date/time to extract from datevalue
The Date value to evaluate
A member of the FirstDayOfWeek enum
A member of the FirstWeekOfYear enum
An Integer containing the specified part
Extracts an individual component of the date or time (like the month or the second) from a date/time value
The DatePart function returns an Integer containing the specified portion of the given date. DatePart is a single function encapsulating the individual Year , Month , Day , Hour , Minute , and Second functions.
interval can be one of the following literal strings:
String | Description |
---|---|
yyyy | Year |
q | Quarter |
m | Month |
y | Day of year |
d | Day |
w | Weekday |
ww | Week |
h | Hour |
n | Minute |
s | Second |
interval can also be a member of the DateInterval enum:
Enum DateInterval Day DayOfYear Hour Minute Month Quarter Second Week Weekday WeekOfYear End Enum
The firstdayofweekvalue argument can be any of the following members of the FirstDayOfWeek enumeration:
Enum FirstDayOfWeek System 'uses first day of week setting on local system Sunday Monday Tuesday Wednesday Thursday Friday Saturday End Enum
The firstdayofweekvalue argument affects only calculations that use either the Week (or "w" ) or Weekday (or "ww" ) interval values.
The firstweekofyearvalue argument can be any of the following members of the FirstWeekOfYear enumeration:
FirstWeekOfYear constant | Value | Description |
---|---|---|
System |
| Uses the local system setting |
Jan1 | 1 | Starts with the week in which January 1 occurs (the default value) |
FirstFourDays | 2 | Starts with the first week that has at least four days in the new year |
FirstFullWeek | 3 | Starts with the first full week of the year |
MsgBox("Current hour: " & DatePart(DateInterval.Hour, Now))
When working with dates, always check that a date is valid using the IsDate function prior to passing it as a function parameter.
If you attempt to extract the hours, minutes, or seconds, but datevalue does not contain the necessary time element, the function assumes a time of midnight (0:00:00).
If you specify datevalue within quotation marks ( " " ) and omit the year, the year is assumed to be the current year taken from the computer's date. For example:
Console.WriteLine(DatePart(DateInterval.Year, cDate("01/03")))
VB 6 lacks the DateInterval enumeration and therefore only accepts a string as the interval argument.
VB 6 supports a number of constants beginning with vb ... as values for the firstdayofweekvalue and firstweekofyearvalue arguments . While these are still supported in VB.NET, VB.NET has also added the FirstDayOfWeek and FirstWeekOfYear enumerations.
DateSerial Function, DateString Property, DateValue Function