How to query mongodb Date using php - php

I need to convert this query from php to mongoDB query
$query = "select * from table where data_added like '%data%';
I have date stored in variable
$date = "2013-09-02";
and in my mongo Document the date sorted as :
$dateAdded = new MongoDate(strtotime('2013-09-02 12:21:55'));
I tried
$date = new MongoDate(strtotime("$date"));
$mongo->find(array('date_added'=>array('$lt'=>$date)));
and
$mongo->find(array('date_added'=>$date));
but without success .
so I need to query usin (Y-m-d) not (Y-m-d h:i:s)
so how to use LIKE query for data in mongo
Thanks

You need to do a range query. Create a timestamp, for example using strtotime(), to get the unix timestamp at the start of the day, and another one and the end of the day.
Depending on if you want these two ends inclusive or exclusive, you then use
// Both points/seconds inclusive
->find(array("date" => array('$gte' => $startOfDay, '$lte' => $endOfDay)));
// Both seconds exclusive
->find(array("date" => array('$gt' => $startOfDay, '$lt' => $endOfDay)));
See http://cookbook.mongodb.org/patterns/date_range/

Related

PHP Combine Date and Time fields to form DateTime

I have 3 separate fields:
// date object in the format yyyy-mm-dd
$service_1_date
// time object in the format 00:00:00
$booking->service_1_time_start
// time object in the format 00:00:00
$booking->service_1_time_end
I have set these up as separate fields because I manipulate them separately in my application.
However as I am creating a Google Calendar event I must pass a datetime object as one value like this:
Event::create([
'name' => 'New Booking',
'startDateTime' => '',
'endDateTime' => '',
]);
In order for me to pass the startDateTime and endDateTime parameters I must first combine my date and time objects. So my question is how do I combine my date and time objects to make it into one datetime object?
it is expecting an instance of Carbon
use it like this:
$newDT = date('Y-m-d H:i:s', strtotime("$service_1_date $booking->service_1_time_start"));

Storing and retrieving dates in Mongodb 3.2 with PHPLIB

Using Mongo and PHP how does one store a datetime type, and then retrieve by date?
This is what I have for inserting, but it stores the date as a string:
$collection->insertOne(['date_created' => '2017-01-02 17:20:15']);
How should I be sending the date to Mongo to store as a datetime type so I can do the proper finds?
Put an instance of this class into the array: http://php.net/manual/en/class.mongodb-bson-utcdatetime.php
You need to use the BSON objects in the PHP arrays: http://php.net/manual/en/book.bson.php
Those get serialized properly before passed to Mongo.
$test = array(
"_id" => 123,
"name" => "This is an example",
"date_created" => new MongoDB\BSON\UTCDateTime(time() * 1000)
);
$collection->insert($test);
The time() is multiplied by 1000, because the constructor wants the milliseconds elapsed since the unix epoch, and time() returns the seconds elapsed since the unix epoch. See: http://php.net/manual/en/mongodb-bson-utcdatetime.construct.php
UPDATE:
To retrive the date/time in ISO format, just convert the UTCDateTime object fist to DateTime:
$date_created = $test["date_created"];
$iso_date = $date_created->toDateTime()->format("Y-m-d H:i:s");

Symfony2: DateTime object not working

I am working with the DateTime object and have this problem to obtain the activity of a specific day.
In the controller I do the following query:
$date = new \DateTime('today');
$activity = $em->getRepository('MyBundle:myEntity')->findOneBy(array(
'activity_date' => $date
));
Result for this query is null, but when I define the parameter date in this way:
$date = new \DateTime('Wednesday, ‎January ‎14, ‎2015');
I get the activity that matches this date. Why doesn't today work?
I believe that commenter #prodigitalson is right. When you say today that is in fact now which is formatted with YYYY-MM-DD HH:MM:SS.
Now, if your DBMS column is of type date, DBMS will first normalize two values and only then proceed with comparing.
If your incoming parameter has a value of 2014-01-14 16:47:20, comparing it to DBMS value of 2014-01-14 00:00:00 will no match the record.
Try the following:
$date = new \DateTime(); // no need for explicit `today`
$date->setTime(0,0,0); // reset hours, minutes and seconds to 0
$activity = $em->getRepository('MyBundle:myEntity')->findOneBy(array(
'activity_date' => $date
));
Will this work?

Mongo date range query using _id in PHP

Being relatively new to mongo, I read in the mongo manual about Optimizing Object IDs.
http://www.mongodb.org/display/DOCS/Optimizing+Object+IDs#OptimizingObjectIDs-Extractinsertiontimesfromidratherthanhavingaseparatetimestampfield.
Going with the recommendation about NOT creating a separate Created_On field, I decided I would later extract out the date from the _id field which is an ObjectID
Now, I have many records all with out a Created_On field.
I am attempting to query for a date range, but am unsure of the syntax:
$start = new MongoDate(strtotime("2012-03-01 00:00:00"));
$end = new MongoDate(strtotime("2012-03-15 00:00:00"));
$collection->find(array('_id' => array('$gt' => $start, '$lte' => $end)));
Always returns 0 results. Although I can query individual records and extract the date from the object.
In PHP, you need to do something like:
function timeToId($ts) {
// turn it into hex
$hexTs = dechex($ts);
// pad it out to 8 chars
$hexTs = str_pad($hexTs, 8, "0", STR_PAD_LEFT);
// make an _id from it
return new MongoId($hexTs."0000000000000000");
}
$start = strtotime("2012-03-01 00:00:00");
$end = strtotime("2012-03-15 00:00:00");
$collection->find(array('_id' => array('$gt' => timeToId($start), '$lte' => timeToId($end))));
Then you can use that to query the _id field.
I wrote a blog post describing the process here: http://www.snailinaturtleneck.com/blog/2011/12/20/querying-for-timestamps-using-objectids/

How to get only date from datetime in CodeIgniter?

I have data in MySQL table like :
ID dates value
1 2011-12-18 10:11:12 test1
2 2011-12-18 12:11:12 test2
3 2011-11-18 10:19:11 test3
When I tried to get value in module it not work, I write code like :
$query=$this->db->get_where('datas', array('dates' => date('Y-m-d')));
I need to get data from whole day like get data only from 2011-12-18.
Thanks
Try This:
$date="2018-09-19";
$this->db->select('*');
$this->db->from('tbl_name');
$this->db->where('DATE(date_time_col)', $date);
$query = $this->db->get();
$res= $query->result();
try with $this->db->like();
so it will be
$query=$this->db->like('dates', array('dates' => date('Y-m-d')));
the % will be added automatically
also you have datas as key, and should be dates based on database structure
You can do the following:
In your table, create an int field with the name ts.
When you insert data into this table, use the time() method to insert a timestamp into ts.
$data = array(
'dates' => '<your date value>' ,
'value' => '<your value>' ,
'ts' => time()
);
$this->db->insert('datas', $data);
Then, when querying:
Use the mktime() method to create a timestamp range for the start & end of today.
$start = mktime() - date('h')*3600;
$end = mktime();
$this->db->where('ts >=', $start);
$this->db->where('ts <=', $end);
Make sure you've indexed the ts column. This will also be faster than the above LIKE method on larger datasets.

Categories