Get last date of this month in php

February 6, 2011 § Leave a comment

we have been moved to new domain www.phprepo.in

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading Get last date of this month in php at PHP Repo.

meta

%d bloggers like this: