Calculating Past and Future dates in PHP

Thursday, August 27, 2009 3:09
Posted in category PHP, Projects, Tutorial

Have you wondered, if there was an easy way to find past and future dates in PHP? I had to work on something similar and to tell the truth I did not know that we had easy way around. Yes, I used to create my own library for this, silly me :( .
the strtotime function of php is very powerful but underutilised function. The strtotime function does not just convert strings to timestamp values but it can perform other functions with the help of its internal language. In this post we will learn about calculating past and future dates with the help of strtotime function.

The strtotime function not only converts the string to timestamp value but can also calculate future and past dates. Lets us see some examples


echo date("d-m-y", strtotime("- 7 days"));

This will print the date 7 days ago from current date. simple, isn’t it? yes we can pass offset values into strtotime. The offset values can be any integer followed by days, weeks, months and years. There are other predefined values like now, today, tomorrow, yesterday, first saturday, last saturday, this saturday, next saturday  and so on.

some more examples to make the concept more clear:

echo date("d-m-y", strtotime("- 7 days"));
echo date("d-m-y", strtotime("+1 weeks"));
echo date("d-m-y", strtotime("- 1 months"));
echo date("d-m-y", strtotime("+ 2 years"));
echo date("d-m-y", strtotime("now"));
echo date("d-m-y", strtotime("yesterday"));
echo date("d-m-y", strtotime("last sunday"));
echo date("d-m-y", strtotime("this monday"));
echo date("d-m-y", strtotime("+2 weeks saturday"));

and in a case where you want to find 10 days from today you can simply use
echo date(“d-m-Y”, strtotime(“+10 days”));

And yes this is that simple. Don’t do it the hard way ;)

VN:F [1.8.3_1051]
Rating: 10.0/10 (1 vote cast)
VN:F [1.8.3_1051]
Rating: +1 (from 3 votes)
Calculating Past and Future dates in PHP10.0101
http://www.sanjeevshrestha.com.np/wp-content/plugins/sociofluid/images/digg_32.png http://www.sanjeevshrestha.com.np/wp-content/plugins/sociofluid/images/reddit_32.png http://www.sanjeevshrestha.com.np/wp-content/plugins/sociofluid/images/stumbleupon_32.png http://www.sanjeevshrestha.com.np/wp-content/plugins/sociofluid/images/delicious_32.png http://www.sanjeevshrestha.com.np/wp-content/plugins/sociofluid/images/blogmarks_32.png http://www.sanjeevshrestha.com.np/wp-content/plugins/sociofluid/images/google_32.png http://www.sanjeevshrestha.com.np/wp-content/plugins/sociofluid/images/myspace_32.png http://www.sanjeevshrestha.com.np/wp-content/plugins/sociofluid/images/facebook_32.png http://www.sanjeevshrestha.com.np/wp-content/plugins/sociofluid/images/yahoobuzz_32.png http://www.sanjeevshrestha.com.np/wp-content/plugins/sociofluid/images/twitter_32.png
You can leave a response, or trackback from your own site.

Leave a Reply