Adding value to a date with PHP

4

I'm having a problem adding a date that comes from the database that comes as follows: Ex .: 05/10/2018 17:48:27 I'm using the following method to add days to that date:

date('d/m/Y H:i:s', strtotime('+10 days', strtotime('10/05/2018 17:48:27')));

But the result is what I get: 10-01-1970 16:00:00

I checked that when the format of the date is with "-" (ie ... 10-05-2018 17:48:27) instead of "/" the sum is successful.

My question is, how would I make this sum work with the pattern I get from the database, as in the example "10/05/2018 17:48:27."

    
asked by anonymous 07.08.2018 / 16:21

1 answer

4

It is always safer in these cases to use DateTime::createFromFormat , since it is you who say to PHP what format should be used to do the parser of the date.

See:

 $datetime = DateTime::createFromFormat('d/m/Y H:i:s', '10/05/2018 17:48:27');

To add the days, just use modify

 $datetime->modify('+10 days');

To display use format

 echo $datetime->format('d/m/Y H:i:s');

Some comments about what you asked the question

  

But the result is what I get: 10-01-1970 16:00:00

Generally, when PHP can not process a date correctly, the date set is this. In some cases, the DateTime class even has errors in the date syntax (in this case, I believe it is the parser used internally of strtotime to do this check);

If you see this example where I use the date_parse function, you'll be able to see how PHP understood its date string .

Example code:

 print_r(date_parse ('10/05/2018 17:48:27'));

The output is:

array(12) {
  ["year"]=>
  int(2018)
  ["month"]=>
  int(10)
  ["day"]=>
  int(5)
  ["hour"]=>
  int(17)
  ["minute"]=>
  int(48)
  ["second"]=>
  int(27)
  ["fraction"]=>
  float(0)
  ["warning_count"]=>
  int(0)
  ["warnings"]=>
  array(0) {
  }
  ["error_count"]=>
  int(0)
  ["errors"]=>
  array(0) {
  }
  ["is_localtime"]=>
  bool(false)
}

Notice that PHP interprets 05 as dia and 10 as month.

  

I checked that when the format of the date is with "-" (ie ... 10-05-2018 17:48:27) instead of "/" the sum is successful.

Yes, functions like strtotime and date_parse or the DateTime class of PHP have a list of pre-defined formats for rendering data , in which the format that is generally used in Brazil is not part of this list.

As I said earlier, just use createFromFormat that your problem is solved.

    
07.08.2018 / 16:26