gpt4 book ai didi

以人类可读格式显示的 PHP 6 位日期代码

转载 作者:可可西里 更新时间:2023-11-01 13:37:34 27 4
gpt4 key购买 nike

我有一组日期格式如下...

197402
192201
184707

前四位代表年份,后两位代表月份。我正在尝试以这种格式输出这些

February 1974
January 1922
July 1847

我试过像这样将它传递给日期函数...

echo date ('F Y', 197402)

但这每次都会给我 1970 年 1 月,所以我想我误解了日期函数的工作原理,有人可以帮忙吗?

最佳答案

您将获得“1970 年 1 月”作为输出,因为您尝试根据 时间戳 197402 创建日期,即从 1970 年 1 月 1 日算起的秒数。如果你从中输出完整的字符串(包括秒数等等),你会看到它是一个有效的时间戳,产生了一个实际日期,但它们都在 1970 年 1 月开始,请参见 online demo .

该格式 YYYYMM 不是大多数函数可识别的格式。您需要将其拆分,如果您知道格式将采用那种方式 - 并改用该数据。您可以使用 substr() 拆分字符串,然后借助 date() 将数字月份转换为与该月份关联的字符串mktime()(因为您只需指定年份和月份)。

下面的片段

$arr = [197402, 192201, 184707];

foreach ($arr as $v) {
$year = substr($v, 0, 4);
$month = substr($v, 4, 2);
echo date("F Y", mktime(0, 0, 0, $month, 0, $year))."<br />"; // mktime() produces a valid timestamp based on just month and year

// Alternatively, drop mktime() and use strtotime() and create from a standard format,
// while specifying a date in the month (which won't matter to the output)
// echo date("F Y", strtotime("$month/01/$year"))."<br />";
}

会输出

February 1974
January 1922
July 1847


或者,您可以使用 DateTime 类(使用起来简单得多),并使用 date_create_from_format()< 从给定格式创建

foreach ($arr as $v) {
echo date_create_from_format('Yh', $v)->format('F Y')."<br />";
}

这将生成与上面相同的输出。

引用资料

关于以人类可读格式显示的 PHP 6 位日期代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41809691/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com