我有一个日期,格式为yyyy-mm-dd
,已从MySQL数据库中提取。此日期将保存到变量$myDate
。
我想将此变量日期前三周的日期保存到名为$otherDate
的 new 变量中。我怎么能这样做(理想情况下,同时更改日期的格式)?
我试过了:
$otherDate = date("l d F", strtotime("-3 weeks", $myDate));
但无济于事。
答案 0 :(得分:2)
了解strtotime
的最佳方法是look at the doc page for it:
预期格式为int strtotime ( string $time [, int $now = time() ] )
参数定义为:
<强>时间强>
日期/时间字符串。有效格式以日期和时间格式说明。
立即强>
时间戳,用作计算相对日期的基础。
因此$otherDate = date("l d F", strtotime("-3 weeks", $myDate));
不正确,因为$myDate
不是整数,而是yyyy-mm-dd
格式的字符串。
您必须将$myDate
传递给包含-3 weeks
修饰符的字符串:
$otherDate = date("l d F", strtotime("$myDate -3 weeks"));
或者,如果您想在$now
参数中重新定义strtotime
:
$otherDate = date("l d F", strtotime("-3 weeks", strtotime($myDate)));
但我建议使用a DateTime
object:
$otherDate = new DateTime($myDate);
$otherDate->sub(new DateInterval('P3W'));
echo $otherDate->format('l d F');
答案 1 :(得分:1)
strtotime()的第二个参数必须是时间戳,而不是字符串,所以
$otherDate = date("l d F", strtotime("-3 weeks", strtotime($myDate)));
但是请看看使用DateTime对象
$date = new \DateTime( $myDate );
$otherDate = clone $date;
$otherDate->sub( new \DateInterval('P3W') );
echo $otherDate->format( 'l d F' );
答案 2 :(得分:1)
由于我发现程序日期操作难看且具有限制性,我将建议使用PHP的真棒DateTime类。
$dt = new DateTime('2014-11-28');
$dt->modify('-3 weeks');
echo $dt->format('l d F');
答案 3 :(得分:0)
因为你使用strtotime错误的方式。 检查一下:
$otherDate = date("l d F", strtotime("2014-11-28 -3 weeks"));
echo $otherDate;
输出:
Friday 07 November