Wednesday, 8 August 2018

PHP: Get The First Monday Of A Month (And More)

This is a small cheat sheet for PHP’s strtotime function, which can be used to convert textual sentences such as “next Friday” and “last Monday” into UNIX timestamps and formatted dates.
In the examples below, I’ve used the format “j, d-M-Y”, which will give you something like: Monday, 17-Aug-2015. You can change this to your format of choice

Get next Monday.

Get next Monday (the result will be relative to today’s date, of course):

Get the first day of a given month.

In this example, I am getting the first Wednesday in December, 2015:
As you can see, the strtotime function is more than capable of converting English sentences into dates and times.

Get next Friday.

If we want to get the date of next Friday:

Get the first day of next month.

Here, we get the first day of next month (relative to today’s date):
Get next Thursday.

Get the first Monday in January.

If we need to get the first Monday in January:
Obviously, you will need to change 2015 to match the year that is relevant to your requirements. For example, if we want the first Monday in January 2016:

First Monday of next month.

Obviously, this is relative to today’s date:

Get the last day of this month.

Need to get the last date of this month? You could even use this to figure out what day of the week it falls on, or how many days are in this month:

Get the last date of last month.

Want to know when last month ended?

Get the second Friday of last month.

Want to know when the second Friday of last month fell on?
As you can see, PHP’s strtotime function is pretty flexible when it comes to taking in text.

Get the last Friday of this month.

The last Friday of a given month can be pretty important to businesses:
Hopefully, you found this cheat sheet to be useful! Be sure to test strtotime out by supplying it with different sentences and whatnot! You can start off by changing words such as “last” to “first” and “second last”, etc.

0 comments:

Post a Comment