Avg. Rating 4.0

Problem

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.

Solution

Use the datePart() function or one of ColdFusion's other functions for the corresponding date part you want to return such as hour(), minute(), second(), month(), day(), dayOfWeek(), week(), month(), quarter(), or year().

Detailed explanation

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 work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes