The question is too long to list here, but basically someone contacted me looking for help with a file review system. The part that was causing issue was the fact that he needed to review the files from the previous day. In order figure out the previous day Tuesday-Friday, it was fine. When it comes to weekend, changing of the month, or changing of the year, he was doing a whole lot of crazy date alterations.
No problem - we've all been there. Until you realize how much Date/Time functionality ColdFusion has built-in, you usually do take it upon yourself to figure out all the logic required to handle things like weekends and year cross-overs. Thankfully, ColdFusion plays very nicely with date math, and when date math is not enough, ColdFusion's DateAdd() function can really pick up the slack. In addition to that, ColdFusion also has Year(), Month(), and Day() functions for parsing out parts of the date/time stamp.
Long story-short, getting the previous day (excluding weekends) is as easy as calling ColdFusion's DateAdd() function with the "w" date part. The "w" date part stands for Weekday. For a long time, I didn't understand the difference between Day and Weekday in the context of DateAdd(). They do basically the same thing, most of the time. The difference, which can be subtle depending on what date you are looking at, is that adding or subtracting Weekdays to and from a date will hop over the weekends. Therefore, if you add a weekday to Friday, it will return the next Monday. Similarly, if you subtract a Weekday from a Monday, it will return the previous Friday.
This being said, getting the previous weekday is quite a simple task. To demonstrate, we will get the previous 10 weekdays (excluding Saturday and Sunday):
<!--- Get the current DATE. Fix()'ing the date will chop off the time portion of the date/time stamp. Caution: This will result in a NUMERIC date, not a standard date. ---> <cfset dtNow = Fix( Now() ) /> <!--- Now, let's loop over the past 10 WEEKDAYS. This is different from days. Weekday math does not include weekends in its calculations. ---> <cfloop index="intOffset" from="0" to="10" step="1"> <!--- Get the WEEKDAY that we want to show. ---> <cfset dtDay = DateAdd( "w", -intOffset, dtNow ) /> <!--- Output the full date so we can see BOTH the day of the week and the day-date. ---> #DateFormat( dtDay, "full" )#<br /> </cfloop>
Running the above code, we get the following output:
Monday, July 23, 2007
Friday, July 20, 2007
Thursday, July 19, 2007
Wednesday, July 18, 2007
Tuesday, July 17, 2007
Monday, July 16, 2007
Friday, July 13, 2007
Thursday, July 12, 2007
Wednesday, July 11, 2007
Tuesday, July 10, 2007
Monday, July 9, 2007
Notice that neither Saturday nor Sunday are showing up in this list. ColdFusion makes life easy.
Want to use code from this post? Check out the license.