在 PHP 中将一种日期格式转换为另一种日期格式

发布于 2024-08-19 21:00:24 字数 314 浏览 6 评论 0 原文

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

但我当然希望它返回当前日期而不是黎明时分。我做错了什么?

Is there a simple way to convert one date format into another date format in PHP?

I have this:

$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

But I'd of course like it to return a current date rather than the crack 'o dawn. What am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

余罪 2024-08-26 21:00:24

date() 的第二个参数需要是正确的时间戳(自 1970 年 1 月 1 日以来的秒数)。您正在传递一个 date() 无法识别的字符串。

您可以使用 strtotime() 进行转换将日期字符串转换为时间戳。但是,即使 strtotime() 也无法识别 ymdhis 格式。

PHP 5.3 及更高版本

使用DateTime::createFromFormat。它允许您使用 date() 语法指定精确的掩码来解析传入的字符串日期。

PHP 5.2 及更低版本

您必须使用 substr() 手动解析元素(年、月、日、时、分、秒)并将结果传递给 mktime() 将为您构建一个时间戳。

但这是很多工作!我建议使用 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);   

The second parameter to date() needs to be a proper timestamp (seconds since January 1, 1970). You are passing a string, which date() can't recognize.

You can use strtotime() to convert a date string into a timestamp. However, even strtotime() doesn't recognize the y-m-d-h-i-s format.

PHP 5.3 and up

Use DateTime::createFromFormat. It allows you to specify an exact mask - using the date() syntax - to parse incoming string dates with.

PHP 5.2 and lower

You will have to parse the elements (year, month, day, hour, minute, second) manually using substr() and hand the results to mktime() that will build you a timestamp.

But that's a lot of work! I recommend using a different format that strftime() can understand. strftime() understands any date input short of the next time joe will slip on the ice. for example, this works:

$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);   
世界和平 2024-08-26 21:00:24

最简单的方法是

$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');

另一个问题也指同一主题: 转换日期格式 yyyy-mm-dd =>日-月-年

The easiest way to do this is

$myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
$newDateString = $myDateTime->format('m/d/Y');

You are first giving it the format $dateString is in. Then you are telling it the format you want $newDateString to be in.

This also avoids the use of strtotime, which can be hard to work with at times.

If you are not transforming from one date format to another, but just want the current date (or datetime) in a specific format then it's even easier:

$now = new DateTime();
$timestring = $now->format('Y-m-d h:i:s');

This other question also refers to the same topic: Convert date format yyyy-mm-dd => dd-mm-yyyy.

躲猫猫 2024-08-26 21:00:24

基础知识

将一种日期格式转换为另一种日期格式的最简单方法是使用 strtotime()<代码>日期()strtotime() 会将日期转换为 Unix 时间戳。然后可以将该 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() 要求日期位于 有效格式。未能提供有效的格式将导致 strtotime() 返回 false,这将导致您的日期为 1969-12-31。

使用DateTime()

从 PHP 5.2 开始,PHP 提供了 DateTime() 类为我们提供了更强大的工具来处理日期(和时间)。我们可以使用 DateTime() 重写上面的代码,如下所示:

$date = new DateTime('2008-07-01T22:35:17.02');
$new_date_format = $date->format('Y-m-d H:i:s');

使用 Unix 时间戳

date() 将 Unix 时间戳作为其第二个参数,为您返回格式化的日期:

$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 位系统来说太大,无法进行数学计算,因此您需要使用 BCMath 库以字符串形式进行数学运算:

$timestamp = bcdiv('1234567899000', '1000');

要获取 Unix 时间戳,您可以使用 strtotime() 返回 Unix 时间戳:

$timestamp = strtotime('1973-04-18');

使用 DateTime(),您可以使用 DateTime::getTimestamp()

$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() 允许我们告诉 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');

The Basics

The simplist way to convert one date format into another is to use strtotime() with date(). strtotime() will convert the date into a Unix Timestamp. That Unix Timestamp can then be passed to date() to convert it to the new format.

$timestamp = strtotime('2008-07-01T22:35:17.02');
$new_date_format = date('Y-m-d H:i:s', $timestamp);

Or as a one-liner:

$new_date_format = date('Y-m-d H:i:s', strtotime('2008-07-01T22:35:17.02'));

Keep in mind that strtotime() requires the date to be in a valid format. Failure to provide a valid format will result in strtotime() returning false which will cause your date to be 1969-12-31.

Using DateTime()

As of PHP 5.2, PHP offered the DateTime() class which offers us more powerful tools for working with dates (and time). We can rewrite the above code using DateTime() as so:

$date = new DateTime('2008-07-01T22:35:17.02');
$new_date_format = $date->format('Y-m-d H:i:s');

Working with Unix timestamps

date() takes a Unix timeatamp as its second parameter and returns a formatted date for you:

$new_date_format = date('Y-m-d H:i:s', '1234567890');

DateTime() works with Unix timestamps by adding an @ before the timestamp:

$date = new DateTime('@1234567890');
$new_date_format = $date->format('Y-m-d H:i:s');

If the timestamp you have is in milliseconds (it may end in 000 and/or the timestamp is thirteen characters long) you will need to convert it to seconds before you can can convert it to another format. There's two ways to do this:

  • Trim the last three digits off using substr()

Trimming the last three digits can be acheived several ways, but using substr() is the easiest:

$timestamp = substr('1234567899000', -3);
  • Divide the substr by 1000

You can also convert the timestamp into seconds by dividing by 1000. Because the timestamp is too large for 32 bit systems to do math on you will need to use the BCMath library to do the math as strings:

$timestamp = bcdiv('1234567899000', '1000');

To get a Unix Timestamp you can use strtotime() which returns a Unix Timestamp:

$timestamp = strtotime('1973-04-18');

With DateTime() you can use DateTime::getTimestamp()

$date = new DateTime('2008-07-01T22:35:17.02');
$timestamp = $date->getTimestamp();

If you're running PHP 5.2 you can use the U formatting option instead:

$date = new DateTime('2008-07-01T22:35:17.02');
$timestamp = $date->format('U');

Working with non-standard and ambiguous date formats

Unfortunately not all dates that a developer has to work with are in a standard format. Fortunately PHP 5.3 provided us with a solution for that. DateTime::createFromFormat() allows us to tell PHP what format a date string is in so it can be successfully parsed into a DateTime object for further manipulation.

$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');

In PHP 5.4 we gained the ability to do class member access on instantiation has been added which allows us to turn our DateTime() code into a one-liner:

$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');
时光沙漏 2024-08-26 21:00:24

试试这个:

$old_date = date('y-m-d-h-i-s');
$new_date = date('Y-m-d H:i:s', strtotime($old_date));

Try this:

$old_date = date('y-m-d-h-i-s');
$new_date = date('Y-m-d H:i:s', strtotime($old_date));
归途 2024-08-26 21:00:24

$datedd-mm-yyyy hh:mm:ss 转换为正确的 MySQL 日期时间
我这样走:

$date = DateTime::createFromFormat('d-m-Y H:i:s',$date)->format('Y-m-d H:i:s');

To convert $date from dd-mm-yyyy hh:mm:ss to a proper MySQL datetime
I go like this:

$date = DateTime::createFromFormat('d-m-Y H:i:s',$date)->format('Y-m-d H:i:s');
青萝楚歌 2024-08-26 21:00:24

以下是将日期转换为不同格式的简单方法。

// 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";

The following is an easy method to convert dates to different formats.

// 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";
一个人练习一个人 2024-08-26 21:00:24
$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); 
$old_date = date('y-m-d-h-i-s');       // works

you are doing wrong here, this should be

$old_date = date('y-m-d h:i:s');       // works

separator of time is ':'


I think this will help...

$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); 

OR


$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); 
听闻余生 2024-08-26 21:00:24

这种本机方式将有助于将任何输入的格式转换为所需的格式。

$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);

This native way will help to convert any inputted format to the desired format.

$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);
够钟 2024-08-26 21:00:24

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

strtotime will work that out. the dates are just not the same and all in us-format.

<?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";
?>
梦一生花开无言 2024-08-26 21:00:24

您需要将 $old_date 转换回时间戳,如 日期函数 需要时间戳作为其第二个参数。

You need to convert the $old_date back into a timestamp, as the date function requires a timestamp as its second argument.

很快妥协 2024-08-26 21:00:24

在 php 中更改日期格式的最简单方法

在 PHP 中,任何日期都可以使用不同的场景转换为所需的日期格式,例如将任何日期格式更改为日、日期月年

$newdate = date("D, d M Y", strtotime($date));

它将以以下非常好的格式显示日期

星期一, 2020 年 11 月 16 日

如果您现有的日期格式也有时间,例如,如果您的日期时间格式为 SQL 2020-11-11 22:00:00,您可以使用以下命令将其转换为所需的日期格式

$newdateformat = date("D, d M Y H:i:s", strtotime($oldateformat));

它将显示日期以下格式美观

2020 年 11 月 15 日星期日 16:26:00

Easiest and simplest way to change date format in php

In PHP any date can be converted into the required date format using different scenarios for example to change any date format into Day, Date Month Year

$newdate = date("D, d M Y", strtotime($date));

It will show date in the following very well format

Mon, 16 Nov 2020

And if you have time as well in your existing date format for example if you have datetime format of SQL 2020-11-11 22:00:00 you can convert this into the required date format using the following

$newdateformat = date("D, d M Y H:i:s", strtotime($oldateformat));

It will show date in following well looking format

Sun, 15 Nov 2020 16:26:00

跨年 2024-08-26 21:00:24

这为我解决了,

$old = '18-04-2018';
$new = date('Y-m-d', strtotime($old));
echo $new;

输出:2018-04-18

This solved for me,

$old = '18-04-2018';
$new = date('Y-m-d', strtotime($old));
echo $new;

Output : 2018-04-18

吻风 2024-08-26 21:00:24

试试这个:

$tempDate = explode('-','03-23-15');
$date = '20'.$tempDate[2].'-'.$tempDate[0].'-'.$tempDate[1];

Try this:

$tempDate = explode('-','03-23-15');
$date = '20'.$tempDate[2].'-'.$tempDate[0].'-'.$tempDate[1];
疯狂的代价 2024-08-26 21:00:24

我知道这已经过时了,但是,在遇到一个在 API 中不一致地使用 5 种不同日期格式的供应商(以及使用从 5 到最新 7 的各种 PHP 版本的测试服务器)时,我决定编写一个通用转换器适用于多种 PHP 版本。

该转换器几乎可以接受任何输入,包括任何标准日期时间格式(包括带或不带毫秒)和任何纪元时间表示形式(包括带或不带毫秒),并将其转换为几乎任何其他格式。

调用它:

$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;    
}
?>

这是一些示例调用 - 您会注意到它还处理任何时区数据(尽管如上所述,任何非 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

此版本中唯一没有的功能是能够选择您希望返回的日期时间所在的时区。最初,我编写此代码是为了将任何日期时间更改为大纪元时间,因此,我不需要时区支持。不过添加起来很简单。

I know this is old, but, in running into a vendor that inconsistently uses 5 different date formats in their APIs (and test servers with a variety of PHP versions from the 5's through the latest 7's), I decided to write a universal converter that works with a myriad of PHP versions.

This converter will take virtually any input, including any standard datetime format (including with or without milliseconds) and any Epoch Time representation (including with or without milliseconds) and convert it to virtually any other format.

To call it:

$TheDateTimeIWant=convertAnyDateTome_toMyDateTime([thedateIhave],[theformatIwant]);

Sending null for the format will make the function return the datetime in Epoch/Unix Time. Otherwise, send any format string that date() supports, as well as with ".u" for milliseconds (I handle milliseconds as well, even though date() returns zeros).

Here's the code:

<?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;    
}
?>

Here's some sample calls - you will note it also handles any time zone data (though as noted above, any non GMT time is returned in your time zone).

$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>";

Here's the output:

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

The only thing not in this version is the ability to select the time zone you want the returned datetime to be in. Originally, I wrote this to change any datetime to Epoch Time, so, I didn't need time zone support. It's trivial to add though.

清秋悲枫 2024-08-26 21:00:24

这是转换日期格式的另一种方法

<?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'; ?>

This is the other way you can convert date format

<?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'; ?>
断念 2024-08-26 21:00:24

仅使用字符串,对我来说是一个很好的解决方案,mysql 的问题较少。检测当前格式并在必要时更改它,此解决方案仅适用于西班牙语/法语格式和英语格式,不使用 php 日期时间函数。

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')

Just using strings, for me is a good solution, less problems with mysql. Detects the current format and changes it if necessary, this solution is only for spanish/french format and english format, without use php datetime function.

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;
 }

USE

dateTranslator::translate($date, 'en')
为你鎻心 2024-08-26 21:00:24

为了完整起见,我使用 Carbon 库添加了一个答案,该库非常常见,并且在 Laravel 框架等大型项目中使用。

Carbon 构造函数 可以传递一个日期字符串(strtotime()) 或 DateTime 对象。如果您正在处理无法轻松解析的日期字符串,Carbon 提供了 Carbon::createFromFormat() 静态创建器方法。

$carbon = new Carbon("January 3 2025 4:28 am");
// or
$date = new \DateTime("January 3 2025 4:28 am");
$carbon = new Carbon($date);
// or
$carbon = Carbon::createFromFormat("Y-d-m/H:i", "2025-03-01/04:28");

现在您已经有了一个原生 Carbon 对象,您可以使用 Carbon::format( ) 方法以您需要的任何格式输出:

echo $carbon->format("l jS \\of F Y h:i A");
// Friday 3rd of January 2025 04:28 AM

有很多辅助方法可以快速输出某些格式,例如 Carbon::toDateTimeString() 其输出为MySQL 格式。

For completeness I'm adding an answer using the Carbon library, which is very common and used in large projects like the Laravel framework.

The Carbon constructor can be passed a date string (anything that is recognized by strtotime()) or a DateTime object. If you're dealing with a date string that can't be parsed easily, Carbon provides the Carbon::createFromFormat() static creator method.

$carbon = new Carbon("January 3 2025 4:28 am");
// or
$date = new \DateTime("January 3 2025 4:28 am");
$carbon = new Carbon($date);
// or
$carbon = Carbon::createFromFormat("Y-d-m/H:i", "2025-03-01/04:28");

Now that you have a native Carbon object, you can use the Carbon::format() method to output it in whatever format you need:

echo $carbon->format("l jS \\of F Y h:i A");
// Friday 3rd of January 2025 04:28 AM

There are a lot of helper methods to quickly output certain formats, such as Carbon::toDateTimeString() which outputs in MySQL format.

栀子花开つ 2024-08-26 21:00:24

TestDome 针对 php 开发人员的问题:

有效字符串具有 / 和 - 输出将类似于该

Array
(
    [0] => 20201215
    [1] => 20161215
)

解决方案:

$dates = array("2020/12/15","15-12-2016","12023121");
$result = array();
foreach($dates as $date){
    $f = explode('/',$date);
    $d = explode('-',$date);
    if(count($d) == 3){
    $myDateTime = DateTime::createFromFormat('d-m-Y', $date);
      $result[] = $newDateString = $myDateTime->format('Ymd');
    
    }elseif(count($f) == 3){
        $myDateTime = DateTime::createFromFormat('Y/m/d', $date);
          $result[] = $newDateString = $myDateTime->format('Ymd');
    }
 
}

TestDome Question for php developer:

Valid String having / and - Output will like that

Array
(
    [0] => 20201215
    [1] => 20161215
)

Solutions:

$dates = array("2020/12/15","15-12-2016","12023121");
$result = array();
foreach($dates as $date){
    $f = explode('/',$date);
    $d = explode('-',$date);
    if(count($d) == 3){
    $myDateTime = DateTime::createFromFormat('d-m-Y', $date);
      $result[] = $newDateString = $myDateTime->format('Ymd');
    
    }elseif(count($f) == 3){
        $myDateTime = DateTime::createFromFormat('Y/m/d', $date);
          $result[] = $newDateString = $myDateTime->format('Ymd');
    }
 
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文