Ask Ben: Getting The Start And End Dates Of The Previous Week In ColdFusion
Hi Ben, Please how do I get beginning of previous week to the end of previous week. I'm working on something that needs last week's date to run today. Thank you.
I do now and will always love working with dates in ColdFusion. The fact that you can seamlessly switch from standard dates to numeric dates and do all kind of fast math on them makes them just a pleasure to work with. Not to mention the fact that date math is generally faster that using methods like DateDiff() and DateAdd(). Anyway, getting to the question above, let's not get distracted by the fact that we are dealing with the "previous" week. What we need to think of is the simple fact that we need to get the start and end dates of week given a date within it. Once we see that, then, as I have demonstrated before, this is simply a matter of a little math:
<!--- Get today's date; but then subtract 7 days from it so that we have "this" day of last week. The Fix() method simply removes the time stamp (and converts date to numeric date). ---> <cfset dtLastWeek = (Fix( Now() ) - 7) /> <!--- Now that we have a day in last week, we can easily grab the start and end of the week. ---> <cfset objLastWeek = StructNew() /> <!--- Get start of week. ---> <cfset objLastWeek.Start = DateFormat( dtLastWeek - DayOfWeek( dtLastWeek ) + 1 ) /> <!--- Get end of week by adding to start date. ---> <cfset objLastWeek.End = DateFormat( objLastWeek.Start + 6 ) /> <!--- Output the week delimiters. ---> <cfoutput> <p> Start: #objLastWeek.Start#<br /> End: #objLastWeek.End# </p> </cfoutput>
The reason that we have to use DateFormat() for the dates when calculating them is that a byproduct of date math is the fact that it turns standard dates into numeric dates; these are date/time stamps represented as floating point values where the integer is the day and the fraction is the time. You can certainly leave the dates in numeric format, but I find that this can confuse people (and will fail calls to IsDate()). By passing the values through the DateFormat() as an intermediary handler, it converts the numeric dates back into standard dates.
Running the above code, we get:
I hope that helps.
Want to use code from this post? Check out the license.
Is it possible to display all the days in the current week beginning on a Monday. For example:
No problem - all you would have to do is get the Monday of the given week, then use a CFLoop to for 7 days.
For more information check out these links:
Is this example providing the previous week or is it providing a span of 7 days which may include last week?
It gets the last week. I goes back 7 days, and then finds the start / end of that week.
This was exactly what I was looking for, but didn't know exactly how to approach it. You've saved me a bunch of time! Cheers