有没有一种简单的方法可以在PHP中把一种日期格式转换成另一种日期格式?
我有这个。
$old_date = date('y-m-d-h-i-s'); // works
$middle = strtotime($old_date); // returns bool(false)
$new_date = date('Y-m-d H:i:s', $middle); // returns 1970-01-01 00:00:00
但我当然希望它能返回一个当前的日期,而不是裂缝'o黎明。我做错了什么?
date()的第二个参数需要是一个合适的时间戳(从1970年1月1日起的秒数)。你传递的是一个字符串,date()无法识别。
你可以使用strtotime()来将日期字符串转换成时间戳。然而,即使strtotime()也不能识别y-m-d-h-i-s
格式。
PHP 5.3及以上版本
使用DateTime::createFromFormat
。它允许你指定一个精确的掩码--使用date()
语法--来解析传入的字符串日期。
PHP 5.2及以下版本
你必须使用substr()
手动解析元素(年、月、日、时、分、秒),并将结果交给mktime(),它将为你建立一个时间戳。
但这是一个很大的工作!我建议使用strftime()能够理解的不同格式。strftime()能够理解任何日期输入,而不是 "下一次Joe会在冰上滑倒"。例如,这样做。
$old_date = date('l, F d y h:i:s'); // returns Saturday, January 30 10 02:06:34
$old_date_timestamp = strtotime($old_date);
$new_date = date('Y-m-d H:i:s', $old_date_timestamp);
最简单的方法是
$myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
$newDateString = $myDateTime->format('m/d/Y');
你首先给它$dateString的格式。 然后你告诉它你希望$newDateString是什么格式。
这也避免了使用strtotime,因为它有时会很难用。
如果你不是要从一种日期格式转换到另一种格式,而只是想让当前的日期(或日期时间)采用特定的格式,那么这就更简单了。
$now = new DateTime();
$timestring = $now->format('Y-m-d h:i:s');
这另一个问题也是指同一个话题。 https://stackoverflow.com/questions/2487921/php-convert-date-format-yyyy-mm-dd-dd-mm-yyyy-not-in-sql。
基础知识
将一种日期格式转换为另一种日期格式的最简单方法是使用[strtotime()
][1]和[date()
][2]。
strtotime()
将日期转换为[Unix时间戳][3]。
然后,Unix时间戳可以传递给date()
,将其转换为新的格式。
$timestamp = strtotime('2008-07-01T22:35:17.02');
$new_date_format = date('Y-m-d H:i:s', $timestamp);
或者作为一个单行本。
$new_date_format = date('Y-m-d H:i:s', strtotime('2008-07-01T22:35:17.02'));
请记住,strtotime()
要求日期为[有效格式][4]。
如果不能提供有效的格式,strtotime()
将返回false,这将导致你的日期是1969-12-31。
**使用`DateTime()``***
从PHP 5.2开始,PHP提供了[DateTime()
][5]类,它为我们提供了更强大的处理日期(和时间)的工具。
我们可以使用DateTime()
重写上面的代码。
$date = new DateTime('2008-07-01T22:35:17.02');
$new_date_format = $date->format('Y-m-d H:i:s');
使用Unix时间戳。
date()
将 Unix timeatamp 作为第二个参数,并返回一个格式化的日期。
$new_date_format = date('Y-m-d H:i:s', '1234567890');
DateTime()通过在时间戳前添加"@"来处理Unix时间戳。
$date = new DateTime('@1234567890');
$new_date_format = $date->format('Y-m-d H:i:s');
如果你拥有的时间戳是以毫秒为单位的(它可能以000
结尾和/或时间戳是13个字符长),你将需要将其转换为秒,然后才能将其转换为其他格式。
有'两种方法可以做到这一点。
substr()
][6]把最后三位数字剪掉。删减最后三位数字有几种方法,但使用substr()
是最简单的。
$timestamp = substr('1234567899000', -3);
你也可以通过除以1000将时间戳转换为秒。 由于时间戳太大,32位系统无法进行数学运算,您需要使用[BCMath][7]库来进行字符串运算。
$timestamp = bcdiv('1234567899000', '1000');
要获得Unix时间戳,你可以使用strtotime()
来返回一个Unix时间戳。
$timestamp = strtotime('1973-04-18');
对于DateTime(),你可以使用[DateTime::getTimestamp()
][8] 。
$date = new DateTime('2008-07-01T22:35:17.02');
$timestamp = $date->getTimestamp();
如果你运行的是 PHP 5.2,你可以使用U
格式化选项来代替。
$date = new DateTime('2008-07-01T22:35:17.02');
$timestamp = $date->format('U');
处理非标准和不明确的日期格式。
不幸的是,并不是所有的日期都是标准格式的。
幸运的是,PHP 5.3 为我们提供了一个解决方案。
[DateTime::createFromFormat()
][9] 允许我们告诉 PHP 日期字符串的格式,这样它就可以成功地被解析成一个 DateTime 对象,以便进一步操作。
$date = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM');
$new_date_format = $date->format('Y-m-d H:i:s');
在PHP 5.4中,我们获得了在实例化时访问类成员的能力,这使得我们可以将DateTime()
的代码变成一句话。
$new_date_format = (new DateTime('2008-07-01T22:35:17.02'))->format('Y-m-d H:i:s');
$new_date_format = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM')->format('Y-m-d H:i:s');
[1]: http://docs.php.net/manual/en/function.strtotime.php [2]: http://docs.php.net/manual/en/function.date.php [3]: http://en.wikipedia.org/wiki/Unix_time [4]: https://php.net/manual/en/datetime.formats.php [5]: http://docs.php.net/manual/en/class.datetime.php [6]: http://php.net/manual/en/function.substr.php [7]: http://php.net/manual/en/book.bc.php [8]: http://php.net/manual/en/datetime.gettimestamp.php [9]: http://docs.php.net/manual/en/datetime.createfromformat.php
将$date
从dd-mm-yyy hh:mm:ss
转换为一个正确的MySQL日期时间。
我是这样走的
$date = DateTime::createFromFormat('d-m-Y H:i:s',$date)->format('Y-m-d H:i:s');
下面是一个简单的将日期转换为不同格式的方法。
// Create a new DateTime object
$date = DateTime::createFromFormat('Y-m-d', '2016-03-25');
// Output the date in different formats
echo $date->format('Y-m-d')."\n";
echo $date->format('d-m-Y')."\n";
echo $date->format('m-d-Y')."\n";
$old_date = date('y-m-d-h-i-s'); // works
你在这里做错了,这应该是
$old_date = date('y-m-d h:i:s'); // works
时间的分隔符是';:'。
我想这个会有帮助...
$old_date = date('y-m-d-h-i-s'); // works
preg_match_all('/(\d+)-(\d+)-(\d+)-(\d+)-(\d+)-(\d+)/', $old_date, $out, PREG_SET_ORDER);
$out = $out[0];
$time = mktime($out[4], $out[5], $out[6], $out[2], $out[3], $out[1]);
$new_date = date('Y-m-d H:i:s', $time);
或
$old_date = date('y-m-d-h-i-s'); // works
$out = explode('-', $old_date);
$time = mktime($out[3], $out[4], $out[5], $out[1], $out[2], $out[0]);
$new_date = date('Y-m-d H:i:s', $time);
这种原生方式将有助于把任何输入的格式转换为所需的格式。
$formatInput = 'd-m-Y'; //Give any format here, this would be converted into your format
$dateInput = '01-02-2018'; //date in above format
$formatOut = 'Y-m-d'; // Your format
$dateOut = DateTime::createFromFormat($formatInput, $dateInput)->format($formatOut);
strtotime会解决这个问题。 日期就是不一样,而且都是美国格式的。
<?php
$e1 = strtotime("2013-07-22T12:00:03Z");
echo date('y.m.d H:i', $e1);
echo "2013-07-22T12:00:03Z";
$e2 = strtotime("2013-07-23T18:18:15Z");
echo date ('y.m.d H:i', $e2);
echo "2013-07-23T18:18:15Z";
$e1 = strtotime("2013-07-21T23:57:04Z");
echo date ('y.m.d H:i', $e2);
echo "2013-07-21T23:57:04Z";
?>
只使用字符串,对我来说是一个很好的解决方案,减少了mysql的问题。 检测当前的格式,并在必要时进行修改,这个解决方案只适用于西班牙/法国格式和英国格式,不需要使用php的datetime函数。
class dateTranslator {
public static function translate($date, $lang) {
$divider = '';
if (empty($date)){
return null;
}
if (strpos($date, '-') !== false) {
$divider = '-';
} else if (strpos($date, '/') !== false) {
$divider = '/';
}
//spanish format DD/MM/YYYY hh:mm
if (strcmp($lang, 'es') == 0) {
$type = explode($divider, $date)[0];
if (strlen($type) == 4) {
$date = self::reverseDate($date,$divider);
}
if (strcmp($divider, '-') == 0) {
$date = str_replace("-", "/", $date);
}
//english format YYYY-MM-DD hh:mm
} else {
$type = explode($divider, $date)[0];
if (strlen($type) == 2) {
$date = self::reverseDate($date,$divider);
}
if (strcmp($divider, '/') == 0) {
$date = str_replace("/", "-", $date);
}
}
return $date;
}
public static function reverseDate($date) {
$date2 = explode(' ', $date);
if (count($date2) == 2) {
$date = implode("-", array_reverse(preg_split("/\D/", $date2[0]))) . ' ' . $date2[1];
} else {
$date = implode("-", array_reverse(preg_split("/\D/", $date)));
}
return $date;
}
使用
dateTranslator::translate($date, 'en')
我知道这是一个老问题了,但是,在遇到一个供应商在他们的API中不一致地使用了5种不同的日期格式(以及测试服务器使用了从5's到最新的7's的各种PHP版本),我决定写一个通用的转换器,适用于无数的PHP版本。
这个转换器几乎可以接受任何输入,包括任何标准的日期时间格式(包括有或没有毫秒)和任何纪元时间表示(包括有或没有毫秒),并将其转换为几乎任何其他格式。
要调用它
$TheDateTimeIWant=convertAnyDateTome_toMyDateTime([thedateIhave],[theformatIwant]);
为格式发送null将使函数以Epoch/Unix时间为单位返回日期时间,否则,发送任何date()支持的格式字符串,以及使用".u"。 否则,发送任何date()支持的格式字符串,以及用".u".表示毫秒(我也处理毫秒,尽管date()返回0)。 为毫秒(我也处理毫秒,即使date()返回0)。
下面是代码。
<?php
function convertAnyDateTime_toMyDateTime($dttm,$dtFormat)
{
if (!isset($dttm))
{
return "";
}
$timepieces = array();
if (is_numeric($dttm))
{
$rettime=$dttm;
}
else
{
$rettime=strtotime($dttm);
if (strpos($dttm,".")>0 and strpos($dttm,"-",strpos($dttm,"."))>0)
{
$rettime=$rettime.substr($dttm,strpos($dttm,"."),strpos($dttm,"-",strpos($dttm,"."))-strpos($dttm,"."));
$timepieces[1]="";
}
else if (strpos($dttm,".")>0 and strpos($dttm,"-",strpos($dttm,"."))==0)
{
preg_match('/([0-9]+)([^0-9]+)/',substr($dttm,strpos($dttm,"."))." ",$timepieces);
$rettime=$rettime.".".$timepieces[1];
}
}
if (isset($dtFormat))
{
// RETURN as ANY date format sent
if (strpos($dtFormat,".u")>0) // Deal with milliseconds
{
$rettime=date($dtFormat,$rettime);
$rettime=substr($rettime,0,strripos($rettime,".")+1).$timepieces[1];
}
else // NO milliseconds wanted
{
$rettime=date($dtFormat,$rettime);
}
}
else
{
// RETURN Epoch Time (do nothing, we already built Epoch Time)
}
return $rettime;
}
?>
这里有一些调用示例--你会注意到它也会处理任何时区数据(尽管如上所述,任何非 GMT 时间都会以你的时区返回)。
$utctime1="2018-10-30T06:10:11.2185007-07:00";
$utctime2="2018-10-30T06:10:11.2185007";
$utctime3="2018-10-30T06:10:11.2185007 PDT";
$utctime4="2018-10-30T13:10:11.2185007Z";
$utctime5="2018-10-30T13:10:11Z";
$dttm="10/30/2018 09:10:11 AM EST";
echo "<pre>";
echo "<b>Epoch Time to a standard format</b><br>";
echo "<br>Epoch Tm: 1540905011 to STD DateTime ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011","Y-m-d H:i:s")."<hr>";
echo "<br>Epoch Tm: 1540905011 to UTC ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011","c");
echo "<br>Epoch Tm: 1540905011.2185007 to UTC ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011.2185007","c")."<hr>";
echo "<b>Returned as Epoch Time (the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.)";
echo "</b><br>";
echo "<br>UTCTime1: ".$utctime1." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime1,null);
echo "<br>UTCTime2: ".$utctime2." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime2,null);
echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,null);
echo "<br>UTCTime4: ".$utctime4." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime4,null);
echo "<br>UTCTime5: ".$utctime5." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime5,null);
echo "<br>NO MILIS: ".$dttm." ----RESULT: ".convertAnyDateTime_toMyDateTime($dttm,null);
echo "<hr>";
echo "<hr>";
echo "<b>Returned as whatever datetime format one desires</b>";
echo "<br>UTCTime1: ".$utctime1." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime1,"Y-m-d H:i:s")." Y-m-d H:i:s";
echo "<br>UTCTime2: ".$utctime2." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime2,"Y-m-d H:i:s.u")." Y-m-d H:i:s.u";
echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,"Y-m-d H:i:s.u")." Y-m-d H:i:s.u";
echo "<p><b>Returned as ISO8601</b>";
echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,"c")." ISO8601";
echo "</pre>";
这里是输出。
Epoch Tm: 1540905011 ----RESULT: 2018-10-30 09:10:11
Epoch Tm: 1540905011 to UTC ----RESULT: 2018-10-30T09:10:11-04:00
Epoch Tm: 1540905011.2185007 to UTC ----RESULT: 2018-10-30T09:10:11-04:00
Returned as Epoch Time (the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.)
UTCTime1: 2018-10-30T06:10:11.2185007-07:00 ----RESULT: 1540905011.2185007
UTCTime2: 2018-10-30T06:10:11.2185007 ----RESULT: 1540894211.2185007
UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 1540905011.2185007
UTCTime4: 2018-10-30T13:10:11.2185007Z ----RESULT: 1540905011.2185007
UTCTime5: 2018-10-30T13:10:11Z ----RESULT: 1540905011
NO MILIS: 10/30/2018 09:10:11 AM EST ----RESULT: 1540908611
Returned as whatever datetime format one desires
UTCTime1: 2018-10-30T06:10:11.2185007-07:00 ----RESULT: 2018-10-30 09:10:11 Y-m-d H:i:s
UTCTime2: 2018-10-30T06:10:11.2185007 ----RESULT: 2018-10-30 06:10:11.2185007 Y-m-d H:i:s.u
UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 2018-10-30 09:10:11.2185007 Y-m-d H:i:s.u
Returned as ISO8601
UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 2018-10-30T09:10:11-04:00 ISO8601
唯一没有在这个版本中的是选择你希望返回的日期时间在哪个时区的能力。 最初,我写这个版本是为了将任何日期时间改为纪元时间,所以,我不需要时区支持。 不过,增加这个功能也是小事一桩。