使用PHP在MongoDB中插入和检索日期和时间戳

4

我正在尝试使用Mongo作为数据库,PHP作为语言来建立一个简单的博客系统。我不确定如何将日期或时间戳放入Mongo中(我猜我需要一个时间戳,以便能够按照它们发布的降序将文章取回)。下面是我现在写的草稿,它创建了一个PHP日期并将其插入其中,但似乎它以字符串形式呈现。在Oracle中我已经习惯了处理这个问题,但是在Mongo中这让我感到惊讶。有什么建议吗?

     try{
        date_default_timezone_set('America/New_York');
        //$dt = date('j-m-y h-i-s');
        $conn = new Mongo(); // connect
        $db = $conn->selectDB("blog");
        $collection = $db->items;
        $item =array(
            'title' => $_POST['title'],
            'txt' => $_POST['txt'],
            'labels' => $_POST['labels'],
            'user' => $_POST['user'],
            'dt' => date('j-m-y h-i-s')
        );
        $collection->insert($item);

        /// disconnect from server
        $conn->close();
    } catch ( MongoConnectionException $e ) {
        echo '<p>Couldn\'t connect to mongodb, is the "mongo" process running?</p>';
        exit();
    }

试试这个:http://www.php.net/manual/zh/class.mongodate.php - Shekhar
2个回答

6

在我看来,最合适的方法是使用MongoDate。因此,要插入它,您需要执行以下操作:

$collection->insert(array(
  'time' => new MongoDate()
));

这将插入当前日期(或在新Mongo 2.6中,您可以使用这种方式)。
或者,
$collection->insert(array(
  'time' => new MongoDate(strtotime("2010-01-15 00:00:00"));
));

将插入特定日期。

要检索您的日期,您可以使用 date('Y-M-d h:i:s', $yourDate->sec);


最新PHP-MONGO驱动程序更新

请使用下面的BSON UTCDateTime类型:

$collection->insert(array(
    'time' => new MongoDB\BSON\UTCDateTime(strtotime("2010-01-15 00:00:00"));
));

3
仅供未来读者参考,MongoDate()对象是指旧版(Nov'16)且不再受支持的Mongo PHP扩展;新驱动程序,即MongoDB,还定义了新类,例如UTCDateTime(http://php.net/manual/en/class.mongodb-bson-utcdatetime.php)。 - Pierpaolo Cira
@PierpaoloCira 谢谢。你也可以编辑我的回答或编写自己的回答。 - Salvador Dali
很抱歉,我的声誉不允许我进行编辑... :( - Pierpaolo Cira

1
你可以使用以下代码在MongoDB中插入日期。将当前日期作为$utcdatetime插入MongoDB。
/********************构造函数**********************************/
$orig_date = new DateTime('2016-06-27 13:03:33');
$orig_date=$orig_date->getTimestamp();
$utcdatetime = new MongoDB\BSON\UTCDateTime($orig_date*1000);

在检索数据时,你可以将毫秒数存储在变量$utcdatetime中,并使用下面的代码来检索UTC时间。/********************检索UTC时间**********************************/
$datetime = $utcdatetime->toDateTime();
$time=$datetime->format(DATE_RSS);

/********************将时间转换为本地时区*******************/

$dateInUTC=$time;
$time = strtotime($dateInUTC.' UTC');
$dateInLocal = date("Y-m-d H:i:s", $time);
echo $dateInLocal;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接