2014-07-25 66 views
0

如果通过的日期不是星期四,我希望​​得到下个星期四相对于特定日期。这是代码已经走了多远。相对于特定日期得到下一个星期四

<?php 

$string = '2014.07.16'; 
$date = DateTime::createFromFormat("Y.m.d", $string); 
$result = $date->format("D"); 
if ($result != 'Thu') 
{ 
$result2 = strtotime('next Thursday'); 
echo date('Y.m.d', $result2); 
} 
?> 

在上面的代码中,变量$ string是通过的日期这是一个“星期三” 我会想获得“2014年7月16日”,这是下一个相对于“2014年7月17日”的星期四。 这意味着如果$ string是一个星期一的'2014.07.21',返回的日期将是'2014.07.24',即下一个星期四相对'2014.07.21' 我现在得到'2014.07.31'这是下个星期四到今天的日期。

如何获得下周四相对于$字符串(通过日期)

的谢谢。

+0

$结果== '星期四' - > $结果= '星期四' – hakiko

+1

尝试' $ result = $ date-> format(“W”);' – Manwal

+0

检查你的措辞。 _'2014.07.16'这是下个星期四相对'2014.07.16'_ –

回答

2

试试这个

$string = '2014.07.16'; 
$date = DateTime::createFromFormat("Y.m.d", $string); 
$result = $date->format("D"); 
if ($result != 'Thu') 
{ 
    $result2 = strtotime('next Thursday', strtotime($date->format("d-M-Y"))); 
    echo date('Y.m.d', $result2); 
} 

OUPUT:! 2014年7月17日

Working Demo

+0

谢谢。这正是我需要的。 – Rebe24

+0

+1比我想象的要简单得多。 –

0

strtotime非常聪明,可以处理所有类型的参数。但是,您需要以不同于您使用的格式传递日期。只需更换。与 - 在将日期传递给strtotime之前:

$string = '2014.07.16'; 
$string = str_replace('.', '-', $string); 

if (date('w', strtotime($string)) != 4) { 
    $date = date('Y.m.d', strtotime($string . ' next thursday')); 
    echo $date; 
} 

date('w')返回星期几为整数。比字符串更好用于比较。

+0

感谢彼得,你是一个很好的考虑。 – Rebe24

相关问题