Reputation: 3200
I am trying to use CreateDate in CFWheels and I am getting stupid errors that I will explain in detail in sec.
To start, this is my code
<cfscript>
lastM = dateFormat(CreateDate(year(now()),month(now())-1,day(now())),'MM');
d = DaysInMonth(lastM);
session.start = dateFormat(CreateDate(Year(rightnow),Month(lastM),Day(01)),'YYYY-MM-DD');
session.end = dateFormat(CreateDate(Year(rightnow),Month(lastM),Day(d)),'YYYY-MM-DD');
session.date = "last_month";
</cfscript>
As you can see I am trying to set my session variables start
and end
to the beginning and end of 'last month'. When I dump lastM
and d
I am getting correct values for the month and the DaysInMonth. When I use these two variables in my CreateDate
method the session.start
is becoming equal to 2013-01-31 and session.end
is equal to 2013-01-30. I tried writing the method in many different ways but I don't see what is causing this.
I have already checked this issue Coldfusion CreateDate Issue here but it is not the same with what I am experiencing.
Upvotes: 0
Views: 596
Reputation: 28873
You are misusing the month()
function. From the docs:
Extracts the month value from a date/time object
You are passing in a number, which CF implicitly converts to a date (probably 01/03/1900), just not the correct one. So month()
is actually returning 1
. That is why your results say January 2013.
A simpler way to accomplish this is to use dateAdd
. Simply calculate the first of the current month. Then subtract months or days to get the start and end of the previous month. (Note: I would leave the values as date objects and only "format" them when you need to display them to the user).
<cfscript>
today = now();
firstOfThisMonth = CreateDate( year(today), month(today), 1);
firstOfLastMonth = dateAdd("m", -1, firstOfThisMonth);
endOfLastMonth = dateAdd("d", -1, firstOfThisMonth);
</cfscript>
Upvotes: 3
Reputation: 1539
Remove your day functions from the last arguments of createDate. Just use 1
and d
.
Upvotes: 0