我正在尝试建立一个简单的博客系统,使用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();
}
在我看来,最合适的方法是使用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);
LASTEST PHP-MONGO驱动程序更新
使用BSON UTCDateTime类型,如下所示:
$collection->insert(array(
'time' => new MongoDB'BSON'UTCDateTime(strtotime("2010-01-15 00:00:00"));
));
您可以使用以下代码在mongodb中插入日期。在mongo数据库中以$utcdatetime的形式插入当前日期。
/********************构造函数**********************************/
$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时间**********************************/
$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;