Does the PHP Datetime class support the creation of dates in the Brazilian format?

Asked

Viewed 207 times

2

In the code below echo be printing +273 days, but the right one wouldn’t be +9 days?

$datetime1 = new DateTime('01/04/2018');
$datetime2 = new DateTime('10/04/2018');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

I don’t understand why, could you help me? Thanks in advance

2 answers

8

YES, SHE SUPPORTS.

To format in DD MM AAAA you can use -, . and \t, but not /:

$datetime1 = new DateTime('01-04-2018'); // poderia ser 01.04.2018 também
$datetime2 = new DateTime('10-04-2018');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

See working on IDEONE

More details in the documentation (see "Localized Notations > Day, month and year"):

https://secure.php.net/manual/en/datetime.formats.date.php

2

You can format the time in several ways by manipulating this object Datetime. The documentation of this php method brings numerous ways to do it.

But as the question refers to the Brazilian format here goes:

$datetime2 = new DateTime('2011-01-01');
var_dump($datetime2->format('d/m/y'));

Exit: string(8) "01/01/11"

Another example:

$datetime1 = new DateTime('2011-01-02');
var_dump($datetime1->format('d*m*y'));

Exit: string(8) "02*01*11"

Make sure the time entered is in the pattern: ('ano-mes-dia'). If no strange things will happen.

Now with the data in perfect order apply your methods:

$interval = $datetime1->diff($datetime2);

echo $interval->format('%R%a days');

Exit: 1

  • "Make sure that the time entered is in the pattern: ('year-month-day'). If no strange things will happen." that I realized, but I was hoping to confirm. so the way and convert the date before. personal thank you very much

  • Be sure to mark an answer as answered

Browser other questions tagged

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