从 yyyymmdd 格式转换为 PHP 中的日期 [英] Converting to date in PHP from yyyymmdd format

查看:39
本文介绍了从 yyyymmdd 格式转换为 PHP 中的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下格式的日期(yyyymmdd、18751104、19140722)...将其转换为 date() 的最简单方法是什么...或者使用 mktime() 和子字符串是我的最佳选择...?

I have dates in the following format (yyyymmdd, 18751104, 19140722)... what's the easiest way to convert it to date().... or is using mktime() and substrings my best option...?

推荐答案

使用strtotime() 将包含日期的字符串转换为 Unix 时间戳:

<?php
// both lines output 813470400
echo strtotime("19951012"), "
",
     strtotime("12 October 1995");
?>

您可以将结果作为第二个参数传递给 date() 自己重新格式化日期:

You can pass the result as the second parameter to date() to reformat the date yourself:

<?php
// prints 1995 Oct 12
echo date("Y M d", strtotime("19951012"));
?>

注意

strtotime() 将失败,日期早于 1970 年初的 Unix 纪元.

Note

strtotime() will fail with dates before the Unix epoch at the start of 1970.

作为替代方案,它适用于 1970 年之前的日期:

As an alternative which will work with dates before 1970:

<?php
// Returns the year as an offset since 1900, negative for years before
$parts = strptime("18951012", "%Y%m%d");
$year = $parts['tm_year'] + 1900; // 1895
$day = $parts['tm_mday']; // 12
$month = $parts['tm_mon']; // 10
?>

这篇关于从 yyyymmdd 格式转换为 PHP 中的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆