0x4B1D
0x4B1D

Reputation: 933

trouble with php dates

I am trying to calculate, based on today's date (24 August 2012), the following three values:

  1. Date of this month's first Saturday.
  2. Date of this month's third Saturday.
  3. Date of next month's first Saturday.

This is how I do it in PHP script:

// Returns August 2012
$this_month = date("F Y");

// Returns September 2012
$next_month = date("F Y", strtotime("next month"));

// Returns August 04th, Saturday
$t_sat_1st=date('U', strtotime($this_month.' First Saturday'));

// Returns August 18th, Saturday
$t_sat_3rd=date('U', strtotime($this_month.' Third Saturday'));

// Returns September 08th, Saturday
$n_sat_1st=date('U', strtotime($next_month.' First Saturday') );

Why is the wrong date returned for the last line of code? I expect it to return September 1st, 2012. What is wrong with my code?

Upvotes: 4

Views: 143

Answers (1)

Kris
Kris

Reputation: 6112

I don't know why your code doesn't exactly work, must be the way it is parsed.. but try

$n_sat_1st=date('U', strtotime('first saturday of ' . $next_month) )

Note the 'of' it is necessary. This code will only work in 5.3+

It should be noted that apparently some of these strings only work in PHP 5.3 apparently, notably:

"first day of this month" and "last day of this month" for example. According to information found on another website, the "xxx day of" feature was added in PHP 5.3.

Comment on this page - http://www.php.net/manual/en/datetime.formats.relative.php

I have tested this on both windows and ubuntu both php 5.3 and 5.4 and it works.

If this does not work, try this

 $d = new DateTime($next_month);
 $d->modify('first saturday of this month');
 echo $d->format('U');

Upvotes: 2

Related Questions