是有一个简单的方法来转换一个日期格式进入另一个日期格式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() 需要一个适当的timestamp(seconds since January1,1970年)。你是通过一串,其日期()可以不承认。

你可以使用 strtotime() 转换的日期串成一个时间戳。然而,即使strtotime()不承认 y-m-d-h-i-s 格式。

PHP5.3和起

使用 DateTime::createFromFormat.它允许指定一个确切的掩模使用 date() 语法分析进入串的日期。

PHP5.2下

你将要分析的单元(年、月、天、小时、分钟,第二次)使用手动 substr() 和手的结果 mktime() 会为你建立一个时间戳。

但是,这是一个很大的工作!我建议使用不同的格式,strftime()可以理解的。strftime()了解 任何 输入的日期短的 the next time joe will slip on the ice.例如,这种工作:

$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,这可能是困难的工作与在次。

如果你不改变从一个日期格式的另一,但只是希望在当前日期(或datetime)在一个特定的格式,那么它甚至更加容易:

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

这种其他问题也是指向同一主题: 转换的日期格式yyyy-mm-dd=>dd-mm-yyyy.

基础知识

Simplist方式来转换一个日期格式转换成另一种是使用 strtotime()date(). strtotime() 会转换的日期进入一个 Unix Timestamp.Unix Timestamp然后可以将传递到 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() 返回的误,这将导致日期以1969-12-31.

使用 DateTime()

As of PHP5.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 timestamps

date() 需要一个Unix timeatamp作为其第二种参数以及返回格式的日期:

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

DateTime()适用Unix timestamps通过增加一个 @ 之前的时间戳:

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

如果你有时间戳是在毫秒(它可以在结束 000 和/或时间戳是十三个字符长)你会需要将其转换为秒前你可以可以将其转换为其他格式。有两种方式来这样做:

  • Trim的最后三位数字使用 substr()

修剪的最后三位数字可以通过几种方式,但使用 substr() 是最简单的:

$timestamp = substr('1234567899000', -3);
  • 分substr通过1000

你也可以转换时间戳到秒除以1000。因为时间戳是太大的32位系统做数学上你会需要使用 BCMath 图书馆做数学题为:

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

得到一个Unix Timestamp可以使用 strtotime() 其返回Unix Timestamp:

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

与DateTime()可以使用 DateTime::getTimestamp()

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

如果你正在运行PHP5.2可以使用 U 格式的选择,而不是:

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

使用非标准和模棱两可的日期格式

不幸的是并不是所有的日期开发人员的工作是在一个标准格式。幸运的是PHP5.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');

在PHP5.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');

尝试这种情况:

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

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

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

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

// 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回一个时间戳,作为日期功能需要时间戳作为它的第二个参数。

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

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

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

尝试这种情况:

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

这解决了对我来说,

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

输出:2018年4月18日

这是可以转换的其他方式日期格式

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

只需使用字符串,对我来说是一个很好的解决方案,问题与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')

我知道这是旧的,但是,在运行到该不一致使用5种不同的日期格式在它们的API(和测试服务器与各种从5分的通过最新7级的PHP版本)的供应商,我决定写一个万能转换器与PHP版本无数作品。

此转换器将实际上任何输入,包括任何标准日期时间格式(包括具有或不具有毫秒)的任何历元的时间表示(包括具有或不具有毫秒)并将其转换为几乎任何其它格式。

要叫它:

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

发送无效的格式将使函数返回在大纪元/ Unix时间的日期时间。否则,发送任何格式的字符串,日期()载体,以及用“.U”为毫秒(I处理毫秒为好,即使日期()返回零)。

下面的代码:

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

在此版本中的唯一一件事就是选择要返回的日期时间要在本来,我写了这个改变任何日期时间到大纪元的时区的能力,所以,我并不需要的时区支持。这是微不足道的,虽然加。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top