first_tuesday()
函数应返回一年中第一个星期二的日期,但特别是在2011年的情况下,它会返回错误的值。如何修复代码,使其适用于所有情况
function first_tuesday($year){
$first_january = mktime(0,0,0,1,1,$year);
$day_week = date("w",$first_january );
$first_tuesday = $first_jan + ((2 - $day_week) % 7)* 86400;
return date("d/m/Y",$first_tuesday);
}
答案 0 :(得分:4)
strtotime
足够聪明,可以得到你想要的东西:
function first_tuesday($year){
return date('d/m/Y', strtotime("first Tuesday of January $year"));
}
答案 1 :(得分:4)
改为使用DateTime
类:
function first_tuesday($year){
$day = new DateTime(sprintf("First Tuesday of January %s", $year));
return $day->format('d/m/Y');
}
用法:
echo first_tuesday(2011);
输出:
04/01/2011
答案 2 :(得分:3)
这似乎对我有用:
<?php
$first_tuesday = new DateTime("first Tuesday of January 2011");
echo $first_tuesday->format('Y-m-d H:i:s');
?>
将其置于功能形式:
<?php
/**
* @return DateTime Returns a DateTime object representing the
* first Tuesday of the year
*/
function first_tuesday($year){
$first_tuesday = new DateTime("first Tuesday of January $year");
return $first_tuesday;
}
?>
如果您只想要格式的字符串,那么:
<?php
/**
* @return DateTime Returns a string representing the first
* Tuesday of the year in the d/m/Y format
*/
function first_tuesday($year){
$first_tuesday = new DateTime("first Tuesday of January $year");
return $first_tuesday->format('d/m/Y');
}
?>
您可以在PHP手册中阅读有关DateTime课程的更多信息(也可以使用法语版本,因为根据原始问题,这似乎是您的母语。)
答案 3 :(得分:0)
$start_of_year = strtotime("01.01.2011");
$first_tuesday = strtotime("tuesday", $start_of_year);
echo date('d.m.Y', $first_tuesday); // 04.01.2011
答案 4 :(得分:0)
简单:
function first_tuesday($year)
{
return date("d/m/Y",strtotime('first Tuesday january '.$year));
}
无需使用对象,这是获取对象的最快方法。