【问题标题】:How to store correctly MongoDB isodate from php script如何从 php 脚本中正确存储 MongoDB isodate
【发布时间】:2017-11-05 09:48:26
【问题描述】:

我想使用 PHP et MongoDB Driver 将日期存储在 MongoDB 集合中。

这是我的部分脚本:

第一次连接:

    public function process(){
    try{
        $this->connexion = new \MongoDB\Driver\Manager($this->dsn);
    }
    catch(\MongoDB\Driver\Exception\InvalidArgumentException $e){
        die("Unable to connect to the MongoDB database : " . $e->getMessage());
    } catch(\MongoDB\Driver\Exception\RuntimeException $e){
        die("General failure : " . $e->getMessage());
    }
}

第二个:文档创建

    public function process(){
    $dbConnector = dbConnector::instance(); // Instance de connexion à la base de données


    $query = new \MongoDB\Driver\BulkWrite;

    $query->insert($this->queryArray);

    $writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
    //$collection = new \MongoCollection($dbConnector->connexion()->db(), $this->store->collectionName());
    try{
        $this->result = $dbConnector->connexion()->executeBulkWrite($dbConnector->dbName() . "." . $this->store->collectionName(), $query, $writeConcern);
    } catch (\MongoDB\Driver\AuthenticationException $e){
        echo "Authentication error : " . $e->getMessage() . "<br />\n";
    } catch(\MongoDB\Driver\ConnextionException $e){
        echo "Connexion error : " . $e->getMessage() . "<br />\n";
    }
    catch(\MongoDB\Driver\Exception\RuntimeException $e){
        echo "Runtime error : " . $e->getMessage() . "<br />\n";
    }
}

$queryArray 属性包含我要创建的键/值对。

添加了一个转换方法,可以管理日期并将其转换为 MongoDB ISODate : 使用 \MongoDB\BSON\UTCDateTime 作为 MongoUTCDate; ... ... 公共静态函数 toISODate($date){ if(is_object($date)){ $dateToString = $date->year 。 “-”。 $日期->月份。 “-”。 $日期->天; } 别的 { $dateToString = substr($date,0,10); } $initDate = new \DateTime($dateToString);

    #begin_debug
    #echo "Date from string " . $dateToString . " : " . $initDate->format("d-m-Y") . " (timestamp) " . $initDate->getTimestamp() . "<br />\n";
    #end_debug

    return new MongoUTCDate($initDate->getTimestamp());
}

我的控制器是这样工作的:

            $stats->_id = $this->requestData()->_id;

        $stats->purchases = [array(
            "date" => \wp\Database\MongoDB\Utilities\MongoDate::toIsoDate($this->requestData()->date),
            "coords" => array("lat" => $this->requestData()->coords->lat, "lon" => $this->requestData()->coords->lon),
            "metar" => null,
            "quantity" => $this->requestData()->quantity,
            "price" => (float) $this->requestData()->price,
            "peremption" => \wp\Database\MongoDB\Utilities\MongoDate::toIsoDate($this->requestData()->peremption)
        )];

        $stats->insert();

调用时,文档已正确创建,但日期错误:

{
"_id" : "3256222010007",
"purchases" : [ 
    {
        "date" : ISODate("1970-01-18T07:43:01.706Z"),
        "coords" : {
            "lat" : 43.7294742,
            "lon" : 1.416332
        },
        "metar" : null,
        "quantity" : 1,
        "price" : 2.87,
        "peremption" : ISODate("1970-01-18T22:20:34.800Z")
    }
]
}

在前面的例子中,日期就是当天的日期...

当我记录数据时,我看到 PHP 中的日期格式正确:

Date from string 2017-06-04 : 04-06-2017 (timestamp) 1496527200<br />

如果转换回时间戳,得到正确的日期......所以,不明白为什么 Mongo 日期不正确。

【问题讨论】:

    标签: php mongodb date


    【解决方案1】:

    对于同样的问题,只需将 PHP 给出的时间戳乘以 1000 即可:

        public static function toISODate($date){
        if(is_object($date)){
            $dateToString = $date->year . "-" . $date->month . "-" . $date->day;
        } else {
            $dateToString = substr($date,0,10);
        }
        $initDate = new \DateTime($dateToString);
    
        #begin_debug
        #echo "Date récupérée à partir de " . $dateToString . " : " . $initDate->format("d-m-Y") . " (timestamp) " . $initDate->getTimestamp() . "<br />\n";
        #end_debug
        $stampedDate = $initDate->getTimestamp() * 1000;
    
        $mongoUTCDate = new MongoUTCDate($stampedDate);
    
        return $mongoUTCDate;
    }
    

    正确的日期被存储...

    【讨论】:

    • 感谢提示multiply by 1000 with timestamp
    猜你喜欢
    • 1970-01-01
    • 2012-09-06
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 2016-04-29
    • 2015-04-21
    • 1970-01-01
    • 2015-10-21
    相关资源
    最近更新 更多