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.
– Carlos
@Carlos takes a look at the edition. The
date_parse
can be your friend in these times.– Wallace Maxters
And how to make comparisons?
– Carlos
@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 bycreateFromFormat
.– Wallace Maxters
@Carlos see How to compare dates in PHP
– Wallace Maxters