php - issue in increase days-date

Viewed 262

im try to increase days(60) in m-d-Y but it is calculate wrong day. it is consider it as d-m-y format.

echo "Today is :: ".date("m-d-Y"); 
echo "\n";       
echo $DateEnd = date('m-d-Y', strtotime(date("m-d-Y") . ' +60 day'));

output is ::

Today is :: 11-07-2017
End date is :: 09-09-2017

Code : https://3v4l.org/jmT9a

any help or suggestion will be appreciated

5 Answers

Cause of problem:- strtotime() Note section:-

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-, the date string is parsed as y-m-d.

Som-d-Y is unrecognised format while adding days to php date.

Do like below:-

<?php

echo "Today is :: ".date("m-d-Y"); 
echo "\n";       
echo $DateEnd = date('m-d-Y', strtotime(date("y-m-d") . '+60 days'));

Outpit: -https://eval.in/894300

Also check possible Php date formats

Try this, It will work for you

<?php

echo "Current Date: ".date("m-d-Y");
echo "\n";
echo $contractDateEnd = date('m-d-Y', strtotime(date("d-m-Y") . ' +60 day'));
?>

You can also use dateinterval:

var_dump (date_create()->add(date_interval_create_from_date_string('60 days')));

Test at ideone

Read the note from the PHP Manual:

Note: Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-, the date string is parsed as y-m-d. To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

So you need to use

echo date("m-d-Y");
echo "\n";
echo $contractDateEnd = date('m-d-Y', strtotime(date("m/d/Y") . ' +60 day'));

DEMO

There are several problems with your code: it gets the current time (a number) and formats the current date as string then (after it concatenates ' +60 day' to it) it parses it again as number just to format it again as string. A lot of useless and power-consuming operations. And the real trouble is the custom date format you use for date and is not supported by PHP for good reasons.

Use the DateTime class to handle date & time operations. It is better than the old date(), strtotime() and the other date & time functions. It can handle multiple time zones, the code is shorter and much clear:

$now = new DateTime();
$end = new DateTime();
$end->add(new DateInterval('P60D'));

echo "Today is :: " . $now->format('m-d-Y') . "\n";
echo "End date is :: " . $end->format('m-d-Y') . "\n";
Related