开发者

Inserting and retriving dates and timestamps in mongodb using PHP

I'm trying to开发者_JS百科 set up a simple blog system using mongo as the db and php as the language. I'm not sure how to put a date or timestamp into mongo (I guess I need a timestamp so I can pull the postings back in the descending order they were posted in). I've posted below what I've written now as a stub - which is creating a PHP date and sticking that in - but that seems to come out as a String. This is something that I'm so used to handling in Oracle that it took me by surprise in mongo. Suggestions?

     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();
    }


In my opinion, the most appropriate way is to use MongoDate. So to insert it, you need to do:

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

This will insert a current date (or in new Mongo 2.6 you can do it this way).

Or

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

Will insert a specific date.

To retrieve your date, you can use date('Y-M-d h:i:s', $yourDate->sec);


LASTEST PHP-MONGO DRIVER UPDATE

use BSON UTCDateTime type as below:

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


You can use below code to insert date in mongo db. Insert current date as $utcdatetime in mongo db.

/********************constructor**********************************/

$orig_date = new DateTime('2016-06-27 13:03:33');
$orig_date=$orig_date->getTimestamp();
$utcdatetime = new MongoDB\BSON\UTCDateTime($orig_date*1000);

While retriving data, milliseconds you get in variable $utcdatetime and use below code /********************retrieve time in UTC**********************************/

$datetime = $utcdatetime->toDateTime();
$time=$datetime->format(DATE_RSS);

/********************Convert time local timezone*******************/

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜