在PHP中将一种日期格式转换为另一种日期格式
在PHP中有没有一种简单的方法可以将一种日期格式转换为另一种日期格式 我有这个:在PHP中将一种日期格式转换为另一种日期格式,php,date,datetime,format,date-conversion,Php,Date,Datetime,Format,Date Conversion,在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 但我当然希望它返回当前
$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
但我当然希望它返回当前日期,而不是“破晓”。我做错了什么?到目前为止的第二个参数需要是自1970年1月1日以来的正确时间戳秒数。您正在传递一个日期无法识别的字符串
可以使用将日期字符串转换为时间戳。然而,即使是strotime也不能识别y-m-d-h-i-s格式
PHP5.3及以上版本
使用。它允许您使用日期语法指定一个精确的掩码来解析传入的字符串日期
PHP5.2及更低版本
您必须使用substr手动解析元素年、月、日、小时、分钟、秒,并将结果交给将为您构建时间戳的用户
但这是一个很大的工作!我建议使用strftime可以理解的不同格式。strftime能够理解任何日期输入,只要乔下一次在冰上滑倒就行了。例如,这项工作:
$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);
您需要将$old_日期转换回时间戳,因为需要时间戳作为其第二个参数。尝试以下操作:
$old_date = date('y-m-d-h-i-s');
$new_date = date('Y-m-d H:i:s', strtotime($old_date));
$tempDate = explode('-','03-23-15');
$date = '20'.$tempDate[2].'-'.$tempDate[0].'-'.$tempDate[1];
你在这里做错了,这应该是
$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);
或
最简单的方法是
$myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
$newDateString = $myDateTime->format('m/d/Y');
首先将$dateString的格式指定给它。然后告诉它$newDateString的格式
这也避免了使用strotime,有时很难使用strotime
如果您不想从一种日期格式转换为另一种格式,而只想将当前日期或日期时间转换为特定格式,则更容易:
$now = new DateTime();
$timestring = $now->format('Y-m-d h:i:s');
另一个问题也涉及同一主题:.将$date从dd-mm-yyyy-hh:mm:ss转换为正确的MySQL日期时间
我是这样说的:
$date = DateTime::createFromFormat('d-m-Y H:i:s',$date)->format('Y-m-d H:i:s');
《华尔街时报》会解决这个问题的。日期不一样,都是美国格式
<?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";
?>
基础
将一种日期格式转换为另一种日期格式最简单的方法是使用。strotime将把日期转换为一个字符串。然后可以将该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'));
请记住,strotime要求日期必须在一个时间段中。未能提供有效格式将导致strotime返回false,这将导致您的日期为1969-12-31
使用日期时间
从PHP5.2开始,PHP提供了类,它为我们提供了处理日期和时间的更强大的工具。我们可以使用DateTime重写上述代码,如下所示:
使用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是最简单的:
$timestamp = substr('1234567899000', -3);
将substr除以1000
您还可以将时间戳除以1000转换为秒。由于时间戳太大,32位系统无法对其进行计算,因此需要使用库以字符串形式进行计算:
$timestamp = bcdiv('1234567899000', '1000');
要获取Unix时间戳,可以使用返回Unix时间戳的strotime:
$timestamp = strtotime('1973-04-18');
使用DateTime,您可以使用
如果您运行的是PHP 5.2,则可以改用U格式选项:
$date = new DateTime('2008-07-01T22:35:17.02');
$timestamp = $date->format('U');
使用非标准和不明确的日期格式
不幸的是,并非开发人员必须处理的所有日期都是标准格式。幸运的是,PHP5.3为我们提供了一个解决方案。允许我们告诉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中,我们获得了在实例化时访问类成员的能力,这允许我们将日期时间代码转换为一行代码:
$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');
试试这个:
$old_date = date('y-m-d-h-i-s');
$new_date = date('Y-m-d H:i:s', strtotime($old_date));
$tempDate = explode('-','03-23-15');
$date = '20'.$tempDate[2].'-'.$tempDate[0].'-'.$tempDate[1];
以下是将日期转换为不同格式的简单方法
// 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";
仅仅使用字符串,对我来说是一个很好的解决方案,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;
}
使用
这是转换日期格式的另一种方法
<?php
$pastDate = "Tuesday 11th October, 2016";
$pastDate = str_replace(",","",$pastDate);
$date = new DateTime($pastDate);
$new_date_format = $date->format('Y-m-d');
echo $new_date_format.' 23:59:59'; ?>
这种原生方式将有助于将任何输入格式转换为所需格式
$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);
这就为我解决了,
$old = '18-04-2018';
$new = date('Y-m-d', strtotime($old));
echo $new;
输出:2018-04-18我知道这已经过时了,但是,在遇到一家供应商在其API和测试服务器中不一致地使用5种不同的日期格式以及从5到最新7的各种PHP版本时,我决定编写一个通用转换器,该转换器可以与各种PHP版本一起工作 这台转换器将运转良好 e几乎任何输入,包括任何标准日期时间格式(包括带或不带毫秒),以及任何纪元时间表示(包括带或不带毫秒),并将其转换为几乎任何其他格式 称之为:
$TheDateTimeIWant=convertAnyDateTome_toMyDateTime([thedateIhave],[theformatIwant]);
为该格式发送null将使函数以Epoch/Unix时间返回日期时间。否则,发送date支持的任何格式字符串,以及使用.u表示毫秒,我也会处理毫秒,即使date返回零
代码如下:
<?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;
}
?>
此版本中唯一没有的功能是选择希望返回的datetime所在的时区。最初,我写这篇文章是为了将任何日期时间更改为大纪元时间,因此,我不需要时区支持。不过,补充一下也没什么大不了的 在php中更改日期格式的最简单方法 在PHP中,可以使用不同的场景将任何日期转换为所需的日期格式,例如将任何日期格式更改为日期、日期、月份和年份
$newdateformat = date("D, d M Y H:i:s", strtotime($oldateformat));
它将以以下非常好的格式显示日期
2020年11月16日,星期一
如果您的现有日期格式中也有时间,例如,如果您的日期时间格式为SQL 2020-11-11 22:00:00,则可以使用以下命令将其转换为所需的日期格式
它将以如下格式显示日期
Sun,2020年11月15日16:26:00为了完整性,我使用碳库添加了一个答案,碳库非常常见,用于大型项目,如Laravel框架 可以向对象或任何对象识别的对象传递日期字符串。如果您处理的是无法轻松解析的日期字符串,Carbon提供了Carbon::createFromFormat静态创建者方法 $carbon=新碳排放2025年1月3日凌晨4:28; //或 $date=new\datetime 2025年1月3日凌晨4:28; $carbon=新的carbon$日期; //或 $carbon=carbon::createFromFormatY-d-m/H:1205-03-01/04:28; 现在您有了一个原生碳对象,您可以使用该方法以所需的任何格式输出它: echo$carbon->format jS\\of F Y h:i A; //2025年1月3日星期五上午04:28
有很多助手方法可以快速输出某些格式,例如Carbon::toDateTimeString,它以MySQL格式输出。是的,当然谢谢,我想将它的GUID文件名转换回正确的日期格式。如果不循环其返回值,preg_match_似乎有点傻。当你只想要一个的时候,为什么要打电话给所有人?这样不行,strotime无法识别格式。我刚试过。同意,我刚输入了发问者的格式代码,应该指定了正确的格式。我已经编辑了回答。我只是想指出这两个问题应该以某种方式联系起来;当然?我已经好几个月了,我已经好几个月了minutes@madlopt~static methods:你说得对。但是如果日期不正确,它就不能创建对象。除非110%确定$date是有效日期并且符合格式,否则不应该链接这些方法。话虽如此,与格式不完全匹配的无效日期将返回:致命错误:对非对象调用成员函数格式。只是抬头一看!诚然,更好的解决方案是分3步完成,中间一步是空检查。非常好的文章注:根据php.net,DateTime是从php核心中的PHP5.2开始存在的,可以在编译时为PHP5.1启用DateTime的实验支持。试试这个2018-01-01T01:30:25。388940303Z@ShoaibRehan那将是什么格式?我不知道这个答案如何给页面增加任何新的价值。几年前有几个答案给出了这种技术。这个无法解释的答案完全忽略了OP的问题。充其量,这是另一个问题的正确答案。这个答案不应该出现在这一页上——它只会使已经膨胀的页面膨胀,破坏研究者的体验。这个无法解释的答案完全忽略了OP的问题。充其量,这是另一个问题的正确答案。这个答案不应该出现在这一页上——它只会使已经膨胀的页面膨胀,破坏研究者的体验。这不是OP的输入。你在回答一个不同的问题。
$TheDateTimeIWant=convertAnyDateTome_toMyDateTime([thedateIhave],[theformatIwant]);
<?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;
}
?>
$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
$newdate = date("D, d M Y", strtotime($date));
$newdateformat = date("D, d M Y H:i:s", strtotime($oldateformat));