Add value to a date with PHP

Asked

Viewed 1,179 times

4

I’m having a problem adding up a date that comes from the database that comes in the following way: Ex.: 10/05/2018 17:48:27 I am 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 of what I get is this: 10-01-1970 16:00:00

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

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

1 answer

4


It’s always safer in these cases to use DateTime::createFromFormat, since it is you who tells PHP what format should be used to parse the date.

Behold:

 $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 on what you put in the question

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

Usually, when PHP cannot process a date correctly, the date is set. In some cases, the class DateTime even has errors in the date syntax (in this case, I believe the parser used internally from strtotime make that check);

If you see that example where I use the function date_parse, you can see how PHP understood its date string.

Sample Code:

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

The exit 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)
}

Note that PHP interprets 05 as dia and the 10 as a month.

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

Yes, functions such as strtotime and date_parse or the class DateTime of PHP have a list of predefined formats to make the date interpretation, in which the format that is usually used in Brazil is not part of this list.

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

  • Excellent! Thank you very much went very well! Thanks for the explanations.

  • 1

    @Carlos takes a look at the edition. The date_parse can be your friend in these times.

  • And how to make comparisons?

  • @Carlos is already another question. But in PHP it’s easy. Just do it DateTime > DateTime('+10 days') for example. Of course you will use the objects you have created by createFromFormat.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.