views:

142

answers:

3

Hi, I'm trying to get the unix time for date strings that are formatted like so:

'second sunday of march 2010'
'first sunday of november 2010'

I was under the impression that strtotime could handle such a string, but apparently not, as this returns false. How can I convert to unix time when given a day of week, which one of those in the month (ie. first, second, etc.), a month and a year.

+3  A: 

This should be possible with strtotime. You could try generating a timestamp of the first day of march using mktime() and adding that as a 2nd parameter (leaving just "first sunday" in the string part):

$timestamp = mktime (0,0,0,3,1,2010);  // 1st of march
$first_sunday = strtotime("first sunday", $timestamp);

Not sure how this will handle the first day (March 1st) actually being a sunday. Make sure you check that out.

Also, and maybe this more reliable, check this out - the poster says he got good results with the following notation (quoting):

<?php
strtotime('+0 week sun nov 2009'); // first sunday in nov 2009
strtotime('+1 week sun nov 2009'); // second sunday
strtotime('-1 week sun nov 2009'); // last sunday in oct 2009
?>

As always with strtotime, whatever you pick, make sure you test well, especially the edge cases (1st day of month is a sunday, last day of last month was a sunday....)

Pekka
Your first solution was clever, but I didn't even try it because your second one worked well. thanks.
Rob
A: 

start here - use the unix command to only return the day of the week:

%u
CheeseConQueso
A: 

Your code works for me on PHP 5.3.0. What version of PHP are you using?

<?php
date_default_timezone_set("Europe/Oslo");
$time_march = strtotime('second sunday of march 2010');
$time_november = strtotime('first sunday of november 2010');
echo date("Y-m-d", $time_march) . " (timestamp: $time_march)\n";
echo date("Y-m-d", $time_november) . " (timestamp: $time_november)\n";
?>

gives:

2010-03-14 (timestamp: 1268521200)
2010-11-07 (timestamp: 1289084400)
Mads Mobæk
5.1.6....stupid web host
Rob