Website Design United States, Website Design California, Website Designing United States, Website Designing California

The Power of PHP's strtotime() function

PHP has a function that allows us to find dates and times that could sometimes be a hassel to figure out.
That function is strtotime() and it allows us to put in English phrases that can help us find a date. If
we combine this function along with PHP's date() function we can easily come up with dates and times that
we can use without complex formulas.

An Example

Let's say that we have a website where we store news events over a period of a few year. Each year we want
to show our visitors what's happening today as well as what was happening a year ago on the very same day.

One method for this would be to do something like the following:

$today = time() - (365 * 24 * 60 * 60);
echo date("l - F j, Y", $today);

// Output example: Tuesday - September 7, 2004

 

Setting the date for a year ago means we need to subtract a specific amount of time from the current time.
In this case it's 365 days * 24 hours * 60 minutes * 60 seconds. It's not too bad is it. But what if it were
a leap year. That would mean we'd need to check if we needed to use 366 days as opposed to 365 days. That would
mean that we need to check something more.

Or we could take advantage of strtotime() and just make a simple statement like:

echo date("l - F j, Y", strtotime("1 year ago"));

// Output example: Tuesday - September 7, 2004

 

Now let's take this a step further. Let's say that for some reason we needed to find the full date and time
1 year 24 days 30 minutes 10 seconds into the future. Off the top of your head can you quickly come up with the
amount of time we'd need to add to our time function if we were to use the 1st source code example?

Don't think too hard about it. Consider how easy it is to use strtotime() for this.

Note: the first echo shows the current date/time, the second echo shows the date/time that we are looking for.

echo date("l jS \of F Y h:i:s A") . "<br />";
echo date("l jS \of F Y h:i:s A", strtotime("1 year 24 days 30 minutes 10 seconds"));

// Output example:
//Wednesday 7th of September 2005 07:54:15 PM
//Sunday 1st of October 2006 08:24:25 PM













 


© 2008-2009 dotnet4all.com