我有一个格式为1 Feb 2013
的日期,我想将其转换为2013-2-1
。这里的php
代码,我使用,但不幸的是,它做一个负操作,而不是串联!
$first_format = "1 Feb 2013";
$explode_date = explode(' ', $first_format);
$final_format = $explode_date[2] . '-2-1';
给出2010
作为结果,而不是2013-2-1
。
我该如何解决这个问题?
使用DateTime
函数,特别是createFromFormat
方法
$first_format = "1 Feb 2013";
$date = DateTime::createFromFormat('j M Y', $first_format);
echo $date->format('Y-n-j');
// Or to store the date in the final format:
$final_format = $date->format('Y-n-j');
使用strtotime()将日期字符串设置为time,然后使用date()函数对其进行格式化
$first_format = "1 Feb 2013";
$final_format = date("Y-n-j",strtotime($first_format));
查看是否有效
$first_format = "1 Feb 2013";
$explode_date = explode(" ", $first_format);
$final_format = trim($explode_date[2]) . " " . "-2-1";
echo $final_format;