I was working on a new feature on MatchMkr earlier today, to allow members to send each other Valentine’s cards.
Now, while the code for this feature will sit on the site all year round, I only want it to be actionable during a set period, in this case 1st until 14th February. The easiest way to do this, is to get the website to do the work…
First, we need to capture the server’s current timestamp:
1 | $timestamp=$_SERVER['REQUEST_TIME']; |
For those of you that don’t know, the timestamp served up by a UNIX server, is the number of seconds that have elapsed since 1st January 1970. This makes working with timestamps unwieldy at times, but also has its advantages.
Now that we know what the time is, we can do a very quick check that the month is February, and that the day is between 1 and 14. First we need to extract these numerical values from the timestamp:
1 2 | $month=date('n', $timestamp); // will return 1 to 12 $day=date('j', $timestamp); // will return 1 to 31 |
Then we can run a conditional statement:
1 2 3 4 5 | if (($day>=1 && $day<15) && ($month=='2')) { // The time falls in our set timescale, do something! } else { // It doesn't, do something else! } |
Quick and easy, I think you’ll agree. And of course, easily adaptable to your own requirements. A source of information which I find invaluable, is the PHP.net page on dates, and this will help you tweak the above code to your heart’s content!
