Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将变量中的值添加到日期php_Php_Date - Fatal编程技术网

将变量中的值添加到日期php

将变量中的值添加到日期php,php,date,Php,Date,如果我有一个像-7这样的数字存储在一个变量中,我如何用这个数量修改php中的日期。这是我到目前为止所拥有的 <?php $the_date = '16 Mar 2018'; $test_sum = '-7'; $date = $the_date; $date = strtotime($date); $date = strtotime($test_sum, $date); echo date('d M Y', $date); ?>

如果我有一个像-7这样的数字存储在一个变量中,我如何用这个数量修改php中的日期。这是我到目前为止所拥有的

<?php 
    $the_date = '16 Mar 2018'; 
    $test_sum = '-7';
    $date = $the_date;
    $date = strtotime($date);
    $date = strtotime($test_sum, $date);
    echo date('d M Y', $date);
?>


但这只是输出的初始日期值

如果要减去天数,只需使用
“-7天”
。如果不指定单位
strotime()
可能不会减去天数

$the_date = '16 Mar 2018'; 
$test_sum = -7;
$date = strtotime(sprintf("%d days", $test_sum), strtotime($the_date));
echo date('d M Y', $date);
strotime接受“-7天”作为参数。 我认为这可能有效:

$the_date = '16 Mar 2018'; 
$test_sum = '-7';
$date = strtotime($the_date);
$date = strtotime("$test_sum day", $date);
echo date('d M Y', $date);
运行:

date('d M Y', strtotime('16 Mar 2018 -7 days'))
将产生:

09 Mar 2018

请尝试使用以下代码:

$the_date = '16-Mar-2018'; 
$test_sum = '-7';
echo date('Y-m-d', strtotime($the_date. $test_sum.' days'));

您需要使用的是
strotime()
此函数的作用是获取包含英文日期格式的字符串,并尝试将其转换为Unix时间戳格式,即自1970年1月1日00:00:00起的秒数

此代码应适用于您:

date('d M Y', strtotime($the_date. $test_sum . ' days'));
这使得2018年3月16日<代码>成为2018年3月09日<代码>

希望这有帮助


更多关于

-7什么?没有单位的数字是没有意义的。您可以在strotime中执行大多数转换,明白了!需要添加“天”。干杯