0

If I have a number like -7 stored in a variable how can I modify a date in php by this amount. Here's what I have so far;

<?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);
?>

But this just output's the initial date value.

2
  • 2
    -7 what? Unit-less numbers are meaningless. You can do most transformations inside strtotime Commented Mar 14, 2018 at 7:31
  • got ya! Need to add 'days'. cheers Commented Mar 14, 2018 at 7:34

5 Answers 5

1

strtotime accepts "-7 day" as argument. I think this may work:

$the_date = '16 Mar 2018'; 
$test_sum = '-7';
$date = strtotime($the_date);
$date = strtotime("$test_sum day", $date);
echo date('d M Y', $date);
Sign up to request clarification or add additional context in comments.

Comments

0

Running:

date('d M Y', strtotime('16 Mar 2018 -7 days'))

would produce:

09 Mar 2018

Comments

0

If you want to subtract days, you can simply use '-7 days'. If you don't specify the unit strtotime() probably doesn't subtracts days.

$the_date = '16 Mar 2018'; 
$test_sum = -7;
$date = strtotime(sprintf("%d days", $test_sum), strtotime($the_date));
echo date('d M Y', $date);

Comments

0

Please try with the following code :

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

Comments

0

What you need to use is strtotime() what this function does is it gets the string containing an English date format and try to convert it into a Unix timestamp formate which is the number of seconds since 1 of January 1970 00:00:00.

This code should work for you:

date('d M Y', strtotime($the_date. $test_sum . ' days'));

This makes this 16 Mar 2018 to this 09 Mar 2018

Hope that this helps.

More about strtotime

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.