Get last date of this month in php

February 6, 2011 § Leave a comment

we have been moved to new domain

This tutorial helps you to find last date of the month. It’s really easy to find it with “date” and “strtotime” functions.

It is a simple as

Last date of this month

echo date("Y-m-d",strtotime("+1 month -1 second"),strtotime(date("Y-m-1")));

Last date of next month

echo date("Y-m-d",strtotime("+2 month -1 second"),strtotime(date("Y-m-1")));

Last date of previous month

echo date("Y-m-d",strtotime("-1 second"),strtotime(date("Y-m-1")));

The logic behind this is quite simple. Any way the first date of every month will be “1” .We only have a confusion on the last date ie., whether it will be 28,29,30 or 31.

So first we will get the first date of this month by `date(“Y-m-1”)`. For eg. which result us `2011-02-01`.With the help of `strtotime` function i can convert the date into Unix time stamp and with the help of the same function i can add 1 month to it. `strtotime(“+1 month”),strtotime(date(“Y-m-1”)));`. So now it return the Unix time stamp corresponding to¬† `2011-03-01`. Subtracting a second from this will result you the last date of this month.

Happy coding.


Where Am I?

You are currently browsing the PHP category at PHP Repo.

%d bloggers like this: