setsab
setsab

Reputation: 339

Date conversion and updating mongodb document using PHP

Progress :
1. I retireved date from a collection. Example format : Fri Oct 05 14:59:31 +0000 2012
2. I was able to change its format.

CODE USED :

         $cur=$col->find(array(),array("created_at"=>1,"_id"=>0));
          // created_at = contains Date value
$cur_all=$col->find();
while($doc=$cur_all->getNext())
{
        $doc2=$cur->getNext();
        $pieces = implode(" ", $doc2);
                    //converted the array to string with space delimiting
        if($pieces!=NULL)
        {
            $date1 = date_create_from_format("D M d G:i:s +O Y", $pieces);
            echo date_format ( $date1 ,  'Y-m-d G:i:s' );
            //This is the format i  would like to update in mongodb..


            $filter = array('_id'=>new MongoId($doc['_id']));
            $update = array('$set'=>array('created_at'=> newMongoDate($date2)));
            $col->update($filter,$update);
        }
}

QUESTION :

Where to create a date object so that it could be updated to the documents in the collection in the expected format? (format : Y-m-d G:i:s )

P.S : I did a lot of research on Stackoverflow (And other places, as well.) but I could not come to any conclusions. That is why this question. Let me know if there are any clarifications

Upvotes: 0

Views: 1500

Answers (2)

chim
chim

Reputation: 8573

look at http://php.net/manual/en/class.mongodate.php

your code should create a date using a unix timestamp

$date2 = ('23rd April 2013');
$update = array('$set'=>array(
                        'created_at'=> new MongoDate(strtotime($date2))
          ));

http://www.php.net/manual/en/function.strtotime.php

Upvotes: 0

Sammaye
Sammaye

Reputation: 43884

Hmm even though you have explained your background well your actual question:

Where to create a date object so that it could be updated to the documents in the collection in the expected format? (format : Y-m-d G:i:s )

Is a bit confusing.

MongoDB will always save the date in one format and one format only when using ISODate: http://en.wikipedia.org/wiki/ISO_8601 (otherwise known as MongoDate in PHP) and it is probably best to not mess with this status quo.

So I would recommend you use the format Y-m-d G:i:s only as display, i.e.:

$date1 = new MongoDate();
var_dump(date('Y-m-d G:i:s', $date1->sec));

And you use the original $date1 object to actually save to the database.

Of course this would change if you were to create a date in your specified format however here is a piece of code for an example:

$date1 = new MongoDate();
$date2 = new MongoDate(strtotime(date ( 'Y-m-d G:i:s', $date1->sec )));
var_dump(date('Y-m-d G:i:s', $date2->sec));

You can use the $date2 as the date to save into MongoDB formed from the specific format you want.

Upvotes: 1

Related Questions