How Can I Tell if a Date Falls within a Specified Time Period?
Hey, Scripting Guy! How can I tell if a date falls within a specified time period?
Hey, JW. By amazing coincidence on our way to work this morning we heard two different commercials, from two different companies, touting “Christmas in July.” That prompted us to answer your question as soon as we got to the office. After all, if these companies had a copy of the script you’re looking for, then maybe they’d know that Christmas doesn’t come in July.
Note. Of course, we could be wrong about that, so maybe you should send all the Scripting Guys a present anyway, just to be on the safe side.
So how do we know that Christmas doesn’t come in July? We simply ran the following script:
dtmStartDate = #7/1/2005# dtmEndDate = #7/31/2005# dtmTargetDate = #12/25/2005#
If dtmTargetDate >= dtmStartDate AND dtmTargetDate <= dtmEndDate Then Wscript.Echo “The target date is within the specified range.” Else Wscript.Echo “The target date is not within the specified range.” End If
As you can see, we begin by assigning values to three variables. The variables dtmStartDate and dtmEndDate represent our date range; in this case, July 1, 2005 through July 31, 2005. The variable dtmTargetDate is the date in question: we want to know if this day (Christmas Day) comes in July.
To do that, we need to know if the target date is greater than or equal to the start date and if the target date is less than or equal to the end date. Here’s the line of code that checks for that:
If dtmTargetDate >= dtmStartDate AND dtmTargetDate <= dtmEndDate Then
In order to be true a date must meet both conditions. December 25, 2005 is greater than or equal to the start date of July 1, 2005, so our target date meets condition 1. However, December 25, 2005 is not less than or equal to July 31, 2005. The target date fails condition 2, which means that the statement is not true. (Remember, both conditions must be true.) As a result, we know that Christmas doesn’t come in July, and we echo a message to that effect. Had both conditions been true, we would have echoed the jolly holiday message, “The target date is within the specified range.”
Hope that helps, JW. Merry Christmas to all and to all a good night.