3

I've been trying to get the code below to work, and while it worked with June it is not working with July.

The below results in a value of 3 for $first_day_of_month when it should be 2 for Tuesday.

$date = strtotime('20140702'); // July 02, 2014
$month = date('m',$date);
$year = date('Y',$date);
$days_in_month = date('t',$date);
$first_day_of_month = date('w', strtotime($year . $month . 01)); // sunday = 0, saturday = 6
christian
  • 2,279
  • 4
  • 31
  • 42
  • May want to remove the line "$days_in_month = date('t',$date);" since it's not related to your question. – Sven Tore Jun 23 '14 at 19:40

3 Answers3

5

The strtotime function supports relative time formats. You can just do this instead:

$date = strtotime('20140702');
$first_date = strtotime('first day of this month', $date);
$first_day_of_month = date('w', $first_date);

The second parameter to strtotime provides the time that the relative format will be relative to. You can use this to easily calculate dates relative to a particular point, as shown above.

Alexis King
  • 43,109
  • 15
  • 131
  • 205
  • I have a format like `mm.YYY`,eg:`07.2017` and i need to find first and last date of this month-year.Please Consider this problem -@Alexis King – ubm Oct 25 '17 at 08:11
2

You would have to cast 01 to a string or else php will compute the time for 2014071 rather 20140701

strtotime($year . $month . '01')
Jason
  • 848
  • 6
  • 17
2

You should look at mktime().

In your case your best approach would be:

$date = strtotime('20140702'); // July 02, 2014
$month = date('m',$date);
$year = date('Y',$date);
$days_in_month = date('t',$date);


$first_day_of_month = date('w', mktime(0,0,0,$month,1,$year)); // sunday = 0, saturday = 6

As a bonus you can also get the last day of the month

$last_date_of_month = mktime(0,0,0,$month+1,0,$year);
Sven Tore
  • 967
  • 6
  • 29