The Complex Made Simple

For work, I had a piece of code that needed to calculate if a certain date fell in between two other days. So I started out writing out this big long function to calculate if a date fell first within the same year as either of the two dates, and if so within the two months, and within the two days. It was ugly, inaccurate, complex and just plain stupid of me to do it that way.

I knew there had to be an easier way so off to PHP.net I went and sure enough there is strtotime. Strtotime converts a string into a Unix timestamp. Turning my function into this:

function in_between_two_dates($first_date, $second_date, $third_date)
{
if(strtotime($first_date) >= strtotime($second_date) && strtotime($first_date) <= strtotime($third_date) )
{ return true; }
else return false;
}

Remember when in doubt: KISS (Keep it simple stupid).

Justin Yost is a full-time Software Engineer and a part time educator. A graduate of Texas Tech University with a bachelor's degree in computer science, Justin relishes programming and learning more about anything and everything. When not working, Justin occasionally gives talks at the local PHP Meetup. In his free time, Justin enjoys backpacking and reading science fiction books.

Tagged with: , , , , , , , , ,
Posted in Programming, Software Code
Short Link: https://justinyost.com?p=471

Leave a Reply

Your email address will not be published. Required fields are marked *

*