您将得到“1970 年 1 月”作为输出,因为您尝试从 时间戳 197402 创建一个日期,即 1970 年 1 月 1 日的秒数。如果您输出完整从那个字符串(包括秒和诸如此类),你会看到它是一个有效的时间戳,产生一个实际的日期,但它们都在 1970 年 1 月开始,见online demo。
该格式 YYYYMM 不是大多数函数可识别的格式。您需要将其拆分,如果您知道格式将采用这种方式 - 并改用该数据。您可以使用substr() 拆分字符串,然后在date() 和mktime() 的帮助下将数字月份转换为与该月份关联的字符串(因为您只需指定年份和月份)。
下面的sn-p
$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 />";
}
会输出
1974 年 2 月
1922 年 1 月
1847 年 7 月
或者,您可以使用 DateTime 类(使用起来要简单得多),并使用date_create_from_format()从给定格式创建
foreach ($arr as $v) {
echo date_create_from_format('Yh', $v)->format('F Y')."<br />";
}
这将产生与上面相同的输出。
参考文献