【问题标题】:PHP Date Format PrecisionPHP 日期格式精度
【发布时间】:2013-02-21 12:12:42
【问题描述】:

有谁知道是否已经有一种方法可以将日期格式化到一定的精度,而无需我写一些东西来重建给定的格式?

例如,假设我有任何格式的日期,但我想使用 PHP DateTimeFormat 将其转换为 Y-m-d H:i:s 格式(参见下面 PHP 站点的示例)

    $date = new DateTime('2000-01-01');
    echo $date->format('Y-m-d H:i:s');
    Result: 2000-01-01 00:00:00

我真正希望它做的不是返回结果中的 H:i:s 部分,如果它从未包含在原始日期中。

目前我能想到的唯一方法是使用 date_parse_from_format,找出缺少的内容,然后对日期格式 'Y-m-d H:i:s' 进行某种字符串处理省略我不需要的部分(混乱的字符串格式,因为这种日期格式可以是任何东西)。

如果我已经错过了一个功能,我只是不想重新发明轮子。

塔乔

编辑:为了更清楚,日期格式字符串和 $date 的精度是可变的,所以我不能对格式字符串进行硬编码,在我得到它之前我不会知道 $date 的精度.

【问题讨论】:

  • 如果您的根本问题是您的用户输入的日期不同,那么您可以考虑在表单中使用日期选择器,那么您所有的日期都会以相同的方式格式化。

标签: php datetime


【解决方案1】:

我认为您必须知道您的 DATE 是什么格式。

<?php
echo 'Current time: ' . date('Y-m-d H:i:s') . "\n";

$format = 'Y-m-d';
$date = DateTime::createFromFormat($format, '2009-02-15');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";

$format = 'Y-m-d H:i:s';
$date = DateTime::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";

$format = 'Y-m-!d H:i:s';
$date = DateTime::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";

$format = '!d';
$date = DateTime::createFromFormat($format, '15');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
?>

【讨论】:

    【解决方案2】:

    preg_match 是您要查找的内容,具体而言:

    if(preg_match('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/',$date)){
       //here do the conversion for "Y-m-d H:i:s"
    }else{
       //here do the conversion for "Y-m-d"
    }
    

    【讨论】:

    • 抱歉,我不是很清楚,我有一个完整的日期格式需要使用(作为一个变量,特定于我保存数据的数据源),我不知道如何确切的日期将是我需要转换的日期,这取决于用户输入。我可以对日期格式进行一些字符串处理,但我只是想知道是否已经有一个函数可以做到这一点。
    • 嗨,谢谢,我想我需要使用类似的东西,但日期可以是任何格式,所以它可能是“m/d/y h:i”之类的。我只是想知道是否有一个我错过的 PHP 函数会以一定的精度返回日期,而不是我搞乱 preg_match 并试图从格式字符串中删除位。我想可能没有 :( 谢谢你的帮助,它至少表明我在正确的轨道上 :)
    • 好的.. 但是您的日期格式可能只是在预赛前将其转换为 y-m-d 格式,因此您的问题将得到解决..
    • @Deepu。我不明白这如何解决问题。如果有人输入了“m/d/yy”并且您使用strtotime 处理它,您将得到 YYYY-MM-DD HH:ii:ss,它比原来的精度更高。
    【解决方案3】:

    使用 strtotime 可以将几乎任何日期格式转换为时间戳。从那里,你可以使用 date() 来设置你想要的格式。

    更多信息:

    http://php.net/manual/en/function.strtotime.php

    http://www.php.net/manual/en/function.date.php

    编辑: date_parse 也可能完成你想要的:

    http://www.php.net/manual/en/function.date-parse.php

    【讨论】:

      【解决方案4】:

      我不认为这是最有效的方法,但它似乎有效。并且可以对其进行调整以允许不同级别的精度。 (我选择了Y-m-d H:i:sY-m-d H:iY-m-d。我不认为Y-m-d H 会有所帮助,但也许您可能会喜欢Y-m-d ha。如果是这样,添加它就很容易了。)

      <?php
      // Output dates at arbitrary precision.
      header ('Content-Type: text/plain');
      
      $input = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
      $date  = new DateTime($input);
      echo format_date($date);
      
      function format_date($date) {
          switch ($date->format('s')) {
          case '00':
              switch ($date->format('H')) {
              case '00':
                  return $date->format('Y-m-d');
              default:
                  return $date->format('Y-m-d H:i');
              }
          default:
              return $date->format('Y-m-d H:i:s');
          }
      }
      

      当然,这不允许该人实际上想要一个恰好是午夜的时间,并明确表示。我不知道报道那个案子对你来说有多重要。

      【讨论】:

        【解决方案5】:

        最好将时间和日期保存为 unix 时间戳而不是其他格式。

        我创建了一个类来处理 php 中的日期和时间。它易于使用且非常有用

        在您的情况下,您可以使用提供的设置器设置年、月、日、小时、分钟和秒,而不是扩展公共函数以获取日期和时间作为您的预期格式。

        <?php
        define("NEW_LINE", "</BR>");
        class scTimestamp
        {
            private $timestamp;
            private $year;
            private $month;
            private $day;
            private $hour;
            private $minute;
            private $second;
        
            public function __construct() 
            {
                register_shutdown_function(array($this,'__destruct'));
                $this->setTimestamp($_SERVER['REQUEST_TIME']);
            }
            public function __destruct()
            {
                unset($this->timestamp);
                unset($this->year);
                unset($this->month);
                unset($this->day);
                unset($this->hour);
                unset($this->minute);
                unset($this->second);
            }
            private function rebuildTimestampFromDate()
            {
                $this->timestamp=mktime($this->hour,$this->minute,$this->second,$this->month,$this->day,$this->year);
            }
            private function rebuildDateFromTimestamp()
            {
                $this->day=date('j',$this->timestamp);
                $this->month=date('n',$this->timestamp);
                $this->year=date('Y',$this->timestamp);
                $this->hour=date('g',$this->timestamp);
                $this->minute=date('G',$this->timestamp);
                $this->second=date('s',$this->timestamp);       
            }
            public function setTimestamp($tempTimestamp)
            {
                $this->timestamp=$tempTimestamp;     
                $this->rebuildDateFromTimestamp();
            }
            public function getTimestamp()
            {
                return $this->timestamp;    
            }
            public function setYear($tempYear)
            {
                $this->year = $tempYear;
                $this->rebuildTimestampFromDate();
            }
            public function getYear()
            {
                return $this->year;
            }
            public function setMonth($tempMonth)
            {
                $this->month = $tempMonth;
                $this->rebuildTimestampFromDate();
            }
            public function getMonth()
            {
                return $this->month;
            }
            public function setDay($tempDay)
            {
                $this->day=$tempDay;
                $this->rebuildTimestampFromDate();
            }
            public function getDay()
            {
                return $this->day;
            }
            public function setHour($tempHour)
            {
                $this->hour = $tempHour;
                $this->rebuildTimestampFromDate();
            }
            public function getHour()
            {
                return $this->hour;
            }
            public function setMinute($tempMinute)
            {
                $this->minute = $tempMinute;
                $this->rebuildTimestampFromDate();
            }
            public function getMinute()
            {
                return $this->minute;
            }
            public function setSecond($tempSecond)
            {
                $this->second = $tempSecond;
                $this->rebuildTimestampFromDate();
            }
            public function getSecond()
            {
                return $this->second;
            }
        
        
            public function getDateDifferenceFromNow()
            {
                return $this->getDateDifferenceFrom($_SERVER['REQUEST_TIME']);
            }
            public function getDateDifferenceFrom($fromDate)
            {
                $return="";
                $sec=" Second";
                $min=" Minute";
                $hrs=" Hour";
                $before=" Before";
                $difference=$fromDate-$this->getTimestamp();
                if($difference<0)
                    $return.="In the Future";
                else if($difference<60)
                {
                    if($difference>1)
                        $sec.="s";
                    $return.= $difference.$sec.$before;
                }
                else if($difference<3600)
                {
                    $difference=intval($difference/60);
                    if($difference>1)
                        $min.="s";
                    $return.=$difference.$min.$before;
                }
                else if($difference<86400)
                {
                    $difference=intval($difference/3600);
                    if($difference>1)
                        $hrs.="s";
                    $return= $difference.$hrs.$before;
                }
                else if($difference<604800)
                {
                    $return.= date("l g:i a",$this->getTimestamp());
                }
                else if($difference<28512000)
                {
                    $return.= date("F j",$this->getTimestamp());
                }
                else
                {
                    $return.= date("F j, Y, g:i a",$this->getTimestamp());
                }
                return $return;
            }
            public function getDateAsString()
            {
                return date("F j, Y",$this->getTimestamp());
            }
            public function getDateTimeAsString()
            {
                return date("F j, Y, g:i a",$this->getTimestamp());
            }
        
        
            public function __toString()
            {
                $return = NEW_LINE."^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^";
                $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE;
                $return.= NEW_LINE."@@ Timestamp: ".$this->getTimestamp()." @@".NEW_LINE;
                $return.= NEW_LINE."@@ Date: ".$this->getDateTimeAsString()." @@".NEW_LINE;
                $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE;
                return $return;
            }
        
        }
        ?>
        

        包含后可以如下使用

        include_once("scTimestamp.php");
        $test=new scTimestamp();
        
        echo $test->getDateAsString();
        
        $test->setTimestamp(1210203200);
        
        echo $test->getDateDifferenceFromNow();
        
        echo $test;
        
        $test->setTimestamp(121020320022);
        echo $test->getYear();
        
        echo $test;
        

        结果是这样的。

        2015 年 6 月 26 日 2008 年 5 月 7 日晚上 11:33 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^ @@ 时间戳:1210203200 @@ @@ 日期:2008 年 5 月 7 日晚上 11:33 @@ ^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^第5804章 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^@@时间戳:121020320022@@ @@日期:5804年12月25日凌晨3点33分@@^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

        这个类可以根据需要使用

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-09-30
          • 2013-01-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多