从 yyyymmdd 格式转换为 PHP 中的日期
题
我的日期格式如下(yyyymmdd、18751104、19140722)...将其转换为 date() 最简单的方法是什么......或者使用 mktime() 和子字符串是我的最佳选择......?
解决方案
使用 strtotime()
将包含日期的字符串转换为 Unix时间戳:
<?php
// both lines output 813470400
echo strtotime("19951012"), "\n",
strtotime("12 October 1995");
?>
您可以将结果作为第二个参数传递给 date()
自己重新格式化日期:
<?php
// prints 1995 Oct 12
echo date("Y M d", strtotime("19951012"));
?>
笔记
strtotime()
如果日期早于 1970 年初的 Unix 纪元,则会失败。
作为适用于 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
?>
其他提示
就个人而言,我只是用SUBSTR(),因为它可能做到这一点的最轻的方式呢。
但这里有一个函数,它的日期,其中你可以指定格式。返回一个关联数组,因此例如可以做(未测试):
$parsed_date = date_parse_from_format('Ymd', $date);
$timestamp = mktime($parsed_date['year'], $parsed_date['month'], $parsed_date['day']);
http://uk.php.net/手动/ EN / function.date-解析从 - format.php
虽然我必须说,我没有找到任何更容易或更有效的不是简单的:
mktime(substr($date, 0, 4), substr($date, 4, 2), substr($date, 6, 2));
看看 strptime
好感谢所有的答案,但1900年的问题似乎困扰着我所有的响应。下面是我使用的应该有人发现它在今后对他们有用的功能的副本。
public static function nice_date($d){
$ms = array(
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
);
$the_return = '';
$the_month = abs(substr($d,4,2));
if ($the_month != 0) {
$the_return .= $ms[$the_month-1];
}
$the_day = abs(substr($d,6,2));
if ($the_day != 0){
$the_return .= ' '.$the_day;
}
$the_year = substr($d,0,4);
if ($the_year != 0){
if ($the_return != '') {
$the_return .= ', ';
}
$the_return .= $the_year;
}
return $the_return;
}
(PHP 5> = 5.3.0,PHP 7):
您可以得到一个DateTime实例有:
$dateTime = \DateTime::createFromFormat('Ymd|', '18951012');
和其转换为一个时间戳记:
$timestamp = $dateTime->getTimestamp();
// -> -2342217600
不隶属于 StackOverflow