如何从字符串中获取日期并对其进行格式化?
How can I grab a date out of a string and format it?
我的服务器上有 PDF 文件保存如下:
945_20140610_Eve_Ikras.pdf
我想把年月日分开来
$file = "945_20140610_Eve_Ikras.pdf";
if(preg_match("/\d{4}\-d{2}\-d{2}/", $file, $match))
print_r($match);
输出:
Array (
[0] => 20140610
)
但我想像这样格式化日期:
2014-06-10
有什么建议吗?
最简单的方法就是创建一个 DateTime
object (Since you have a special format here you have to use DateTime::createFromFormat
to create your object) and then you can format your date as you want it with format()
,例如
$file = "945_20140610_Eve_Ikras.pdf";
if(preg_match("/\d{4}\d{2}\d{2}/", $file, $match)) {
$date = DateTime::createFromFormat("Ymd", $match[0]);
echo $date->format("Y-m-d");
}
输出:
2014-06-10
我的服务器上有 PDF 文件保存如下:
945_20140610_Eve_Ikras.pdf
我想把年月日分开来
$file = "945_20140610_Eve_Ikras.pdf";
if(preg_match("/\d{4}\-d{2}\-d{2}/", $file, $match))
print_r($match);
输出:
Array (
[0] => 20140610
)
但我想像这样格式化日期:
2014-06-10
有什么建议吗?
最简单的方法就是创建一个 DateTime
object (Since you have a special format here you have to use DateTime::createFromFormat
to create your object) and then you can format your date as you want it with format()
,例如
$file = "945_20140610_Eve_Ikras.pdf";
if(preg_match("/\d{4}\d{2}\d{2}/", $file, $match)) {
$date = DateTime::createFromFormat("Ymd", $match[0]);
echo $date->format("Y-m-d");
}
输出:
2014-06-10