PHP

How to make date in Portuguese in PHP – date function

January 16, 2022

How to make date in Portuguese in PHP – date function

In this article we will learn how to make date in Portuguese in PHP – using the strftime or DateTime function to achieve our goal.

make date in Portuguese in PHP cover

Hey you programmer, how are you? Let’s learn more about PHP and how to create dates in our pattern!

We have two approaches to format dates in Portuguese and we don’t need to use the date function, as many people think

Using DateTime

The way I like the most is using an object called DateTime, so I don’t need to change PHP settings

Let’s see in practice how it works:

<?php

$date = new DateTime();

$formatter = new IntlDateFormatter(
'pt_BR',
IntlDateFormatter::FULL,
IntlDateFormatter::NONE,
'America/Sao_Paulo', 
IntlDateFormatter::GREGORIAN
);

echo $formatter->format($date);

Here we instantiate the DateTime object in the date variable, then we instantiate another IntlDateFormatter object that will be the formatter, that is, where we will configure how our date will appear

Key points are the pt_BR language, timezone like America/Sao_Paulo and also the Gregorian calendar

The output is:

sexta-feira, 8 de maio de 2020

Of course this is based on the date I’m writing the article, you can manipulate the DateTime to put the date you need and then format it

For example:

$date2 = new DateTime('2020-09-08');

Then it will generate the new date as year-month-day

Using strftime

I don’t really like this approach because you change the locale directly from PHP, but it works too

Here you will also change the default timezone, what can happen is your server is in another timezone and generate some instability in your software

See an example:

setlocale(LC_TIME, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese');

date_default_timezone_set('America/Sao_Paulo');

echo strftime('%A, %d de %B de %Y', strtotime('today'));

Here, in the same way, we set the locale to pt_BR and also the timezone to America/Sao_Paulo

The difference is that the date was passed via strtotime instead of the DateTime object

And also pre-formatted into a string, the result will be this:

sexta, 08 de maio de 2020

String formatting can be seen in detail how it works here

Conclusion

In this article we learned how to generate a date in Portuguese in PHP

We applied two approaches, an object oriented with DateTime and another with the strftime method, where we change the PHP configs

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x