且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从yyyymmdd格式转换为PHP的日期

更新时间:2023-11-29 12:37:34

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

 <?php 
//两行输出813470400
echo strtotime(19951012),\\\

strtotime(1995年10月12日);
?>

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

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



注意



strtotime()将在1970年初之前的Unix纪元之前的日期失败。



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

 <?php 
//返回年份自1900年以来的偏移量,在$ b前的年份为负$ b $ parts = strptime(18951012,%Y%m%d);
$ year = $ parts ['tm_year'] + 1900; // 1895
$ day = $ parts ['tm_mday']; // 12
$ month = $ parts ['tm_mon']; // 10
?>


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...?

Use strtotime() to convert a string containing a date into a Unix timestamp:

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

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"));
?>

Note

strtotime() will fail with dates before the Unix epoch at the start of 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
?>