PHP: date “F” with setlocale not working

和自甴很熟 提交于 2019-12-23 12:00:00

问题


<ul>
    <?php
    $event_date = get_sub_field('event_date'); // 20150203
    $event_date_format = DateTime::createFromFormat('Ymd', $event_date);
    setlocale(LC_ALL, 'de_DE');
    ?>  
    <li>
        <h6><?php echo $event_date_format->format('d');?>. <?php echo $event_date_format->format('F');?></h6>
        <p><?php echo $event_date_format->format('H');?>:<?php echo $event_date_format->format('i');?></p>
    </li>
</ul>

The output of this is

03. February 
19:25

Why does setlocale not have any impact on this. I want my Month "F" to be in german like 3. Feber 19:25

Any idea what I'm doing wrong here?


UPDATE 1:

If I try using strftime() i suddenly get a different date output. it is in german but wrong?

<ul>
        <?php
        $event_date = get_sub_field('event_date');
        $event_date_format = DateTime::createFromFormat('Ymd', $event_date);
        setlocale(LC_ALL, 'de_DE');
        ?>  
        <li>
            <h6><?php echo $event_date_format->format('d');?>. <?php echo strftime('%B', $event_date);?></h6>
            <p><?php echo $event_date_format->format('H');?>:<?php echo $event_date_format->format('i');?></p>
        </li>
    </ul>

Suddenly the output date is not 03. February but 03. August, even though the date should be February.

Any ideas?


UPDATE 2:

This is pretty weird. I just checked the variable $event_date online in a unix conversion tool and the I get this … 

$event_date: 20150203

Sat, 22 Aug 1970 05:16:43 GMT

The value is set inside a wordpress backend with a datepicker and clearly says 03/02/2015


回答1:


date() and DateTime do not respect locale

use strftime()

http://php.net/manual/en/function.strftime.php

http://php.net/manual/en/function.date.php

To format dates in other languages, you should use the setlocale() and strftime() functions instead of date().




回答2:


Annoyingly, date is not locale-aware. From the manual:

To format dates in other languages, you should use the setlocale() and strftime() functions instead of date.

You probably want:

setlocale(LC_TIME, 'de_DE');
echo strftime('%B');

Alternatively, checkout Carbon. It's got a consistent API that includes locale-awareness. As an example:

setlocale(LC_TIME, 'German');
echo Carbon::now()->formatLocalized('%B'); // Sonntag


来源:https://stackoverflow.com/questions/30291207/php-date-f-with-setlocale-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!