【问题标题】:display a date in particular format from month array in php在php中以特定格式显示月份数组中的日期
【发布时间】:2020-08-08 16:15:10
【问题描述】:

我有一个如下所示的 php 代码,其中有一个法国月份数组。

<?php
$months = array(
    1 => "janvier",
    2 => "février",
    3 => "mars",
    4 => "avril",
    5 => "mai",
    6 => "juin",
    7 => "juillet",
    8 => "août",
    9 => "septembre",
    10 => "octobre",
    11 => "novembre",
    12 => "décembre",
);
?>

问题陈述:

我想要实现的是我想以以下格式显示日期:

08 août 2020

对于每月的第一天,将 er 附加到数字:

e.g. 1er août 2020

这是我尝试过的。虽然它作为Line A prints 08 août 2020 工作,但我想知道它是否适用于所有情况。这里的所有情况都是指一个月中的所有日子。

我已经硬编码了 Z 行的值,但它会改变。

<?php
$months = array(
    1 => "janvier",
    2 => "février",
    3 => "mars",
    4 => "avril",
    5 => "mai",
    6 => "juin",
    7 => "juillet",
    8 => "août",
    9 => "septembre",
    10 => "octobre",
    11 => "novembre",
    12 => "décembre",
);
$this_date="2020-08-08";   // Line Z 
$this_time = strtotime($this_date);
$day = date('d', $this_time);
$month = date('n', $this_time);
$month_fr = $months[$month];
$suffix = $day == 1 ? 'er' : '';
$formatted_new_fr = strftime("%d$suffix " . $month_fr . " %Y", $this_time);
echo $formatted_new_fr;  // Line A
?>

【问题讨论】:

  • 我正要发布一些技巧,但它们更像是代码审查。我认为这个问题不适合这个网站,因为它实际上并没有指定问题(据你所知,你的代码有效);也许它可以发布在codereview.stackexchange.com 上? (请务必先阅读他们的帮助页面。)
  • @xNoJustice 时区与月份名称有什么关系?您是否将其与“语言环境”混淆了?

标签: php arrays date french


【解决方案1】:

PHP 帮你搞定 :)

setlocale(LC_TIME, 'fr_FR');

$dateString = '2020-08-08';
$timestamp = strtotime($dateString);
$formattedDate = strftime('%d %B %Y', $timestamp);
//setlocale(LC_ALL, Locale::getDefault()); // restore (if neccessary)

echo utf8_encode($formattedDate);

输出

08 août 2020

工作example

要获得1er 日,您可以做您已经做过的事情。只需拆分 strftime(或其结果)。

参考


另一种解决方案(虽然会按顺序显示所有天)

$locale = 'fr_FR';
$dateString = '2020-08-01';
$date = new DateTimeImmutable($dateString);
$dateFormatter = new IntlDateFormatter(
    $locale,
    IntlDateFormatter::FULL,
    NULL
);

$numberFormatter = new NumberFormatter($locale, NumberFormatter::ORDINAL);
$ordinalDay = $numberFormatter->format($date->format('d'));
$dateFormatter->setPattern('LLLL Y');

echo $ordinalDay . ' ' . $dateFormatter->format($date->getTimestamp());

输出

1er août 2020

工作example

参考

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 2012-05-10
    • 2019-05-05
    • 2015-05-18
    • 2022-07-27
    相关资源
    最近更新 更多