1

i cant get this to work. I want to enter a date in d/m/Y and add it days and get the result in d/m/y too but apparently php takes the original input of the date as m/d/Y anyways

<?php

$ymd = DateTime::createFromFormat('d/m/Y', '01/04/2018')- 
>format('d/m/Y');
echo date('d/m/Y', strtotime($ymd. ' + 5 days'));

The output is 09/01/2018 but it is actually taking the 04 in the date input as days when it is the month. The result should be 06/04/2018. How can i get this to work? I tried everything. Thanks.

  • Possible duplicate of [Adding days to $Date in PHP](https://stackoverflow.com/questions/3727615/adding-days-to-date-in-php) –  Feb 17 '19 at 20:24

1 Answers1

0

This is because strtotime() sees 01/04/2018 as month/day/year as when it sees slahes (/) it assumes US format. What Datetime() is doing is irrelevant here as it already has executed and created a date string for you. You need to convert that date into a format that strtotime() recognizes as a European date if you want it to add days correctly.

$ymd = DateTime::createFromFormat('d/m/Y', '01/04/2018')->format('m/d/Y');
echo date('d/m/Y', strtotime($ymd. ' + 5 days'));

Demo

Additionally, I don't know why you are using both DateTime() and strtotime() when DateTime() already can do everything you need:

echo DateTime::createFromFormat('d/m/Y', '01/04/2018')->modify('+5 days')->format('d/m/Y');

Demo

John Conde
  • 217,595
  • 99
  • 455
  • 496