简体   繁体   中英

PHP Date Format Precision

Does anyone know if there's already a way of formatting dates to a certain precision, without me writing something to rebuild the given format?

For example, say I have a date in whatever format, but I want to convert it to Ymd H:i:s format, using the PHP DateTimeFormat (see example from PHP site below)

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

What I really want it to do is not return the H:i:s part in the result if it was never included in the original date.

At the moment the only way I can think of doing this is using date_parse_from_format , work out what's missing and then do some kind of string processing on the date format 'Ymd H:i:s' to omit the parts that I don't need (messy string formatting since this date format could be anything).

I just don't want to re-invent the wheel if there's already a function out there I've missed.

Ta, Jo

EDIT: To try to be more clear, the date format string and the precision of $date are variable so I can't hard code the format string, and I won't know the precision of $date until I get it.

preg_match is what you are looking for, specifically:

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

I think you have to know what format is your 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";
?>

Use strtotime to convert pretty much any date format into a timestamp. From there, you can use date() to set the format however you want it.

For more info:

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

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

Edit: date_parse might also accomplish what you want:

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

I don't think this is the most efficient method, but it seems to work. And it could be tweaked to allow different levels of precision. (I picked Ymd H:i:s , Ymd H:i , and Ymd . I didn't think Ymd H would be helpful, but perhaps you might like Ymd ha . If so, it would be easy enough to add it.)

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

Of course, this does not allow for the possibility that the person actually wanted a time of precisely midnight, and explicitely said so. I don't know how important it is for you to cover that case.

It is best way to save time and date as unix timestamp rather than other formats.

I have created a class to handle date and time in php. Its easy to use and very very useful

In your case, you can set year, month, day, hour, minute and second using the setter provided, than extend a public function to get date and time as your expected format.

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

}
?>

once it is included it can be used as follow

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;

And the result would like this.

June 26, 2015May 7, 2008, 11:33 pm ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ Timestamp: 1210203200 @@ @@ Date: May 7, 2008, 11:33 pm @@ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 5804 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ Timestamp: 121020320022 @@ @@ Date: December 25, 5804, 3:33 am @@ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

This class can be used as per needs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM