DatePart - VBScript
DatePart
VB Script Function – Extracts a specified part of a date.
Syntax
DatePart(interval, Date)
Where:
- interval is the part of the date to be extracted.
- Date is the date value from which the interval is to be extracted.
Valid intervals
- “y” – Year (1 to 9999)
- “q” – Quarter (1 to 4)
- “m” – Month (1 to 12)
- “d” – Day (1 to 31)
- “w” – Day of the week (1 to 7)
- “ww” – Week of the year (1 to 53)
- “h” – Hour (0 to 23)
- “n” – Minute (0 to 59)
- “s” – Second (0 to 59)
- “ms” – Millisecond (0 to 999)
Examples
WScript.Echo DatePart("y", Date)
' Output: The current year
WScript.Echo DatePart("q", Date)
' Output: The current quarter
WScript.Echo DatePart("m", Date)
' Output: The current month
WScript.Echo DatePart("d", Date)
' Output: The current day of the month
WScript.Echo DatePart("w", Date)
' Output: The current day of the week (1-7)
Common Issues
- Make sure to use a valid date format.
- The interval must be enclosed in double quotes.
- DatePart cannot be used to extract parts of a time value.
Integration
DatePart can be combined with other VB Script functions to perform complex date calculations. For example, the following script adds one month to a given date:
Dim date1
date1 = "2023-03-08"
Dim newDate
newDate = DateAdd("m", 1, date1)
WScript.Echo newDate
' Output: 2023-04-08
Related Commands
- DateAdd – Adds an interval to a date.
- DateDiff – Calculates the difference between two dates.
- FormatDateTime – Formats a date according to a specified format string.