Reputation: 611
I have the command date('d.m.y', strtotime('22.02.21 +1 days'))
. The expected output would be 23.02.21, however I am getting 26.02.21. It adds four days, not one. When trying to add two days, it adds five.
Using a different date-format (i.e. date('d.m.y', strtotime('02/22/21 +1 days'))
) works, however I'd like to use this date format, if possible.
Is there a way to make strtotime()
work with this format?
Upvotes: 1
Views: 292
Reputation: 1605
If you are having a two digit year you need to disambiguate the century anyway. Using a four digit year will work.
In this example any year starting 70 is assumed to be in the 20th century while all other years are in the 21st century.
$inputDate = '22.02.21';
$year = substr($inputDate, 6);
if ( $year > 69 ) {
$year = '19' . $year;
} else {
$year = '20' . $year;
}
$date = substr($inputDate, 0, 6) . $year;
echo date("d.m.y", strtotime($date . ' +1 day'));
Sandbox example: http://sandbox.onlinephpfunctions.com/code/14a79178f8909f3078666ae630163fa7c943cff1
Upvotes: 0
Reputation: 725
According to https://www.php.net/manual/en/function.strtotime.php.
strtotime expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp.
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(.) visibly, 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 (-) or a dot(.) visibly, the date string is parsed as y-m-d.
date("d.m.y", strtotime("2021-02-22 +1 day"))
To avoid confusion it is better to use a date with the year on 4 digits
date('d.m.y', strtotime('22.02.2021 +1 days'))
And finally, to avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
Upvotes: 2