开发者

Converting from a day of week to unix time in PHP

开发者 https://www.devze.com 2022-12-24 03:07 出处:网络
I\'m trying to get the unix time for date strings that are formatted like so: \'sec开发者_如何学运维ond sunday of march 2010\'

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

'sec开发者_如何学运维ond 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.


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....)


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消