Printing A MongoDB Date From PHP

前端 未结 5 436
忘了有多久
忘了有多久 2020-12-28 17:53

How in PHP do I get the regular timestamp format out of a MongoDB date?

Assume I have:

$my_date;
print_r($my_date);
         


        
相关标签:
5条回答
  • 2020-12-28 18:23

    Just a quick update, to say that MongoDate has a toDateTime method since the version 1.6 of the pecl extension. You can now do

    $mongoDate->toDateTime()->format(...)
    
    0 讨论(0)
  • 2020-12-28 18:25

    Use MongoDB\BSON\UTCDateTime MongoDate is deprecated

    $mongoDate = new \MongoDB\BSON\UTCDateTime(strtotime('2020-10-01 18:30:00'));
    
    0 讨论(0)
  • 2020-12-28 18:36

    $my_date->sec is the unix timestamp, use date() function to show it in required format.

    echo date('Y-m-d H:i:s', $my_date->sec);
    
    0 讨论(0)
  • 2020-12-28 18:38

    you are missing the microsecond.

    To show (mongo -> php)

    $fecha = date(preg_replace('`(?<!\\\\)u`', $my_date->usec, 'Y-M-d H:i:s.u'), $my_date->sec);
    //MongoDate ISODate("2013-05-28T15:27:24.735Z")
    //Php Date 2013-May-28 10:27:24.735000
    

    To send to mongo (php -> mongo)

    $fecha_mongo = new MongoDate(strtotime($fecha));
    //Fail function, the short way but, 70000 isn't equal to 700000.
    //$fecha_mongo->usec = (int)$fecha_micro->format("u");
    preg_match("/\.(.*)/", $fecha, $uSec);
    $fecha_mongo->usec = (int)(count($uSec)==2?$uSec[1]:0);
    
    //Php Date 2013-May-28 10:27:24.735000
    //MongoDate ISODate("2013-05-28T15:27:24.735Z")
    

    Good day!

    Mario T.

    0 讨论(0)
  • 2020-12-28 18:45

    First, create date from millisecond using given function:

    public function showdatefn($mili)
    {   
        $seconds = (string)$mili / 1000;
        return date("d-m-Y", $seconds); 
    }   
    $date =$this->showdatefn(<put mongo date here>);
    

    This will give you correct date.

    0 讨论(0)
提交回复
热议问题