Technology

PHP: How Many Days until Christmas?

Christmas DogWe have a client who has a special that is only good until Christmas and the setting for the days until expiration is in a field saved in the database.

I needed to write a cron job (scheduled job) that updates the field for each of their restaurants on a nightly basis. I had never scripted any cron jobs before – thanks to my colleague, Tim, at Imavex for leading me in the right direction. I’ve even got it emailing me in the morning to let me know it was successful.

Anyways, I figured since I had written the code anyways, I could share in the fun and get it out to you folks:

$month = 12;
$day = 25;
$year = date("Y");
$days = (int)((mktime (0,0,0,$month,$day,$year) - time(void))/86400);
if ($days>0) {
$year = $year + 1;
$days = (int)((mktime (0,0,0,$month,$day,$year) - time(void))/86400);
}
switch ($days) {
case 0:
echo "Merry Christmas!";
break;
case 1:
echo "It's Christmas Eve!";
break;
default:
echo "There are ".$days." more days until Christmas!";
}

Beware of copy and pasting from the post, sometimes the apostrophes get messed up. If you have WordPress, you could actually insert this into the code of your page and have it display. I’m not sure everyone is excited about Christmas only being 48 days away, but what the heck!

If you wanted to, you could even build out the case statement and do the 12 days of Christmas. 🙂

This code also takes the year into consideration, so next year it will continue to work!

4 Comments

  1. 1
  2. 3

    Hi Doug,

    Thanks for this snippet of code. 🙂 I’m trying to put it on my blog’s sidebar as a widget. I pasted the code in and it’s just showing raw code on the page.. Not being a php wizard.. Is there any “simple” way to get it to work?

    Thanks,
    Dan

Leave a Reply