Finding the last day of the month

Pretty simple equation to show the last day of a month. First, get the first day of next month.

<cfset createdNextMonthDate = CreateDate(year(Now()),month(dateAdd('m',1,Now())),1)>

Then we'll simply subtract one day from that new date.

<cfset lastDayOfMonthForAdStartDate = dateAdd('d',-1,createdNextMonthDate)>

You could put this all into one long line, but I split it up for easier readability.

If you want to set it up as a function, the pass in the date as "datePassed" to the following code, and you will get the last day in that month:

<cffunction name="getLastDayOfMonth" access="public" returntype="date">
<cfargument name="datePassed" type="date" required="Yes">

<cfset createdNextMonthDate = CreateDate(year(arguments.datePassed),month(dateAdd('m',1,arguments.datePassed)),1)>
<cfset lastDayOfMonthForAdStartDate = dateAdd('d',-1,createdNextMonthDate)>

<cfreturn lastDayOfMonthForAdStartDate>

</cffunction>

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Rob O's Gravatar I know this is an older entry, but I thought I'd share a snip of code I wrote for invoicing. You can use DaysInMonth(), built into CF, rather than jumping around with multiple variables:
[code]
<cffunction name="LastDayOfMonth" access="public" returntype="date">
   <cfargument name="Date" type="date" required="yes">
   <cfreturn CreateDate(year(Arguments.Date),month(Arguments.Date),DaysInMonth(Arguments.Date))>
</cffunction>
[/code]
# Posted By Rob O | 6/23/08 1:14 PM
Eno's Gravatar Thanks, Rob O - I'm doing an invoicing app as well and this helps.

( please wait a year to reply like veryone else!)
# Posted By Eno | 5/3/09 8:43 AM
Aubrey Olson's Gravatar Your code is incorrect

<cfset createdNextMonthDate = CreateDate(year(Now()),month(dateAdd('m',1,Now())),1)>

will cause the program to hiccup.

12/01/2009 with be converted into 01/01/2008

it needs to be

<cfset createdNextMonthDate = dateFormat(dateAdd('d', -1,dateAdd('m',1,CreateDate(year(theMonth),month(theMonth),1))),'mm/dd/yyyy')>
# Posted By Aubrey Olson | 4/8/10 12:32 PM
BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.