Notice: With the launch of Adobe Cookbooks, this site will no longer be accepting new entries or posting new content. Thanks to everyone who submitted content!

You need to extract the day/month/year/hour/minute/second (DMYHMS), day of the week/year, week number, or quarter from a date/time object.

DatePart() accepts two parameters, the datepart you want to extract, and the date you want to extract the date part from:

<cfset thedate = createdatetime(2002, 12, 31, 23, 59, 59)>

<cfoutput>
#DateFormat(TheDate, 'dddd mmmm dd, yyyy')# #TimeFormat(TheDate, 'hh:mm:ss tt')#
<p>

<b>Second:</b> #DatePart('s', TheDate)#<br>
<b>Minute:</b> #DatePart('n', TheDate)#<br>
<b>Hour:</b> #DatePart('h', TheDate)#<br>
<b>Week:</b> #DatePart('ww', TheDate)#<br>
<b>Day:</b> #DatePart('d', TheDate)#<br>
<b>Day of week:</b> #DatePart('w', TheDate)#<br>
<b>Day of year:</b> #DatePart('y', TheDate)#<br>
<b>Month:</b> #DatePart('m', TheDate)#<br>
<b>Quarter:</b> #DatePart('q', TheDate)#<br>
<b>Year:</b> #DatePart('yyyy', TheDate)#
</cfoutput>

Running the code produces this output:

Tuesday December 31, 2002 11:59:59 PM
Second: 59
Minute: 59
Hour: 23
Week: 53
Day: 31
Day of week: 3
Day of year: 365
Month: 12
Quarter: 4
Year: 2002

ColdFusion also has a separate function that corresponds to each date part available in the DatePart() function. These functions are often used in lieu of DatePart() as they offer "shorthand" syntax for extracting a date part.

<cfset thedate = createdatetime(2002, 12, 31, 23, 59, 59)>

<cfoutput>
#DateFormat(TheDate, 'dddd mmmm dd, yyyy')# #TimeFormat(TheDate, 'hh:mm:ss tt')#
<p>

Second: #Second(TheDate)#<br>
Minute: #Minute(TheDate)#<br>
Hour: #Hour(TheDate)#<br>
Day: #Day(TheDate)#<br>
Day of week: #DayOfWeek(TheDate)#<br>
Day of year: #DayOfYear(TheDate)#<br>
Week: #Week(TheDate)#<br>
Month: #Month(TheDate)#<br>
Quarter: #Quarter(TheDate)#<br>
Year: #Year(TheDate)#<br>
</cfoutput>

Running this code produces the exact same output as the DatePart() example.

You can get the string representation for the day of week, and month parts of a date object by using the DayOfWeekAsString() and MonthAsString() respectively.

<cfset thedate = createdatetime(2002, 12, 31, 19, 30, 55)>

<cfoutput>
#DayOfWeekAsString(DayOfWeek(TheDate))#<br>
#MonthAsString(Month(TheDate))#
</cfoutput>

This returns:

Tuesday
December


This question was written by Rob Brooks-Bilson.
It was last updated on January 6, 2006 at 1:06:52 PM EST.

CFML Referenced

MonthAsString()
DatePart()
<cfoutput>
DayOfWeekAsString()

Categories

Dates/Times

Comments

There are no comments for this entry.