-1

I am trying to get the date of the first of the month in PHP.

I found this page http://www.php.net/manual/en/datetime.formats.relative.php where it seems you can do 'first day of...' but I don't see how you specify this month.

I also found The first day of the current month in php using date_modify as DateTime object and in the second answer I see you can do

date('Y-m-01');

The latter looks simple, but I don't understand how it specifies the current month. If someone can explain this to me, and also explain the difference in the two methods, that would be a big help!

Community
  • 1
  • 1
user1015214
  • 2,733
  • 10
  • 36
  • 66
  • 1
    http://php.net/manual/en/function.date.php – Karoly Horvath Aug 06 '13 at 19:58
  • The default for the second parameter for [date](http://www.php.net/date) is the current date. For if formats the date with year and month of the current time then hard codes a 01 for the day – Orangepill Aug 06 '13 at 19:58
  • first day is always `1` its not like end day of the month which can be `30,31` and sometimes `28,29` –  Aug 06 '13 at 20:00

2 Answers2

3
$date = new DateTime('first day of this month');
echo $date->format('Y-m-d');
John Conde
  • 217,595
  • 99
  • 455
  • 496
0

Ok here is my explaination, the php date() function actually has two inputs but one is optional. The first is the returned format, the second is the time you are converting to a string formatted date. If the second input isn't set it assumes you mean now, so all of these are the same:

date('Y-m-d');
date('Y-m-d',time());
date('Y-m-d',strtotime('now'));

So when you put in date('Y-m-01') it is pulling the year and month of now but you aren't making the day dynamic, you are forcing it to 01. So in reality here is what you are doing:

$date = date('Y-m') . '-01';

And of course this is server-side so it is based off of the server's clock.

Pitchinnate
  • 7,517
  • 1
  • 20
  • 37