menu

Questions & Answers

How to convert my object date to strftime with Laravel?

I've a data stored in my database in the column date. If I print my data, I have 2017-05-16 00:00:00.

Now, I would like (in French), 16 mai 2017. I heard about sftrtime, but I can not seem to use it. Can you help me please ?

I tried strftime($article->date) and strftime('%A %d %B', $article->date) but it doesn't work.

Answers(4) :

If date is in the $dates array, then it's a Carbon instance, so you can do this:

setlocale(LC_TIME, 'fr_FR');
$date->formatLocalized('%A %d %B %Y');

If not, just use parse() method to parse string to get Carbon instance and then use formatLocalized()

http://carbon.nesbot.com/docs/

Comments:
2023-01-22 23:30:07
I try your method, but the date returned is in English. In my model Article, I create a method getDateForHuman() and I try this setlocale(LC_TIME, 'fr_FR'); return Carbon::parse($this->date)->formatLocalized('%d %B %Y');. In my view, I try $article->getDateForHuman(). Result is in English. You are why?

it is always good idea to consult official manual: http://php.net/manual/en/function.strftime.php

sample code for french:

$timestamp = gmmktime(0,0,0,5,16,2017);
if (!setlocale(LC_ALL, 'fr_FR')) die('Cannot set locale');
echo strftime('%e %B %Y', $timestamp);
Comments:
2023-01-22 23:30:07
Yes… but I don't have a timestamp but a field type "date" in my database
2023-01-22 23:30:07
@Jeremy then you can google how to parse string into timestamp

Try this.

setlocale(LC_ALL, 'fr');
return \Carbon\Carbon::parse($article->date)->formatLocalized('%A %d %B %Y');

// mardi 16 mai 2017
Comments:
2023-01-22 23:30:07
I try your method, but the date returned is in English. In my model Article, I create a method getDateForHuman() and I try this setlocale(LC_ALL, 'fr'); return Carbon::parse($this->date)->formatLocalized('%d %B %Y');. In my view, I try $article->getDateForHuman(). Result is in English. You are why?
2023-01-22 23:30:07
You need to verify if you have the locale installed in your server.

Try this :)

setlocale(LC_ALL, 'IND');
$tanggal = date_create($item->tanggal_masuk);
$tgl =  \Carbon\Carbon::parse($tanggal)->formatLocalized('%d-%m-%Y');
echo $tgl;