My collection structure is as:
{a,b,time}
I am inserting data in the collection through a java service where a and b are integers and time is Date field.
On selecting a field from php I am getting the response as following:
Array
(
[0] => Array
(
[b] => 19511297
[time] => Array
(
[$date] => Array
(
[$numberLong] => 1516688016000
)
)
)
)
How to get the time in the format as through the php function date('Y-m-d H:i:s) ?
Seems like your epoch timestamp is in milliseconds, so you need to do something like this:
$array[0]['time']['$date']['$numberLong'] = 1516688016000;
$timestamp = $array[0]['time']['$date']['$numberLong'] / 1000;
echo date("Y-m-d H:i:s", $timestamp);
It looks like $numberLong contains unix-timestamp, hence you can try something like this:
$data[0]['time']['$date']['date'] = date(
'Y-m-d H:i:s',
$data[0]['time']['$date']['$numberLong'] / 1000
);
You have to use correct MongoDB library first.
When you will extract data from database a datetime field in PHP would be represented as UTCDateTime.
When you had it converted to array it was like ['$date']['$numberLong']. But you don't have to do that.
When you will get a list of documents from your collection, you can iterate over cursor and extract date and time in any convenient format using toDateTime() method in conjunction with format() later.
Look at the example below:
$cursor = $collection->find([]);
foreach ($cursor as $doc) {
echo "\n" . $doc['time']->toDateTime()->format("Y-m-d H:i:s");
}
One of advantages here is that you are not loosing accuracy. The other advantage is that you can deal with timezones in a very efficient way.
For example, if you want to display date and time in IST timezone, you can do it like this:
$timezone = new DateTimeZone('Asia/Kolkata');
foreach ($cursor as $doc) {
echo "\n" . $doc['time']->toDateTime()->setTimeZone($timezone)->format("Y-m-d H:i:s");
}
I recommend you to take a look at Robo 3T (formerly Robomongo), it will help you to work with MongoDB.
Related
Im reading an excel file a column with values like "1:45:00. But when print_r($value["time"]) this value from my array I got a Carbon object like this:
Carbon\Carbon Object
(
[date] => 2018-10-30 01:45:00.000000
[timezone_type] => 3
[timezone] => America/US
)
Then, when I insert to a bulk array my value with:
"time"=>$value["time"]
In the database I got: 2018-10-30 01:45:00
How can I insert only 01:45:00 and not the entire timestamp?
EDIT: I thought that $value["time"]->date->format("H:i:s") would works but I got the error "Trying to get property 'date' of non-object"
EDIT 2: This is how I read the data:
The excel is like:
date time
---------- -------
30-10-2018 01:45:00
The code where I read the excel:
$data = Excel::selectSheetsByIndex(0)->load($path, function($reader) {
})->get()->toArray();
foreach ($data as $key => $value) {
$time = Carbon::createFromFormat('Y-m-d h:i:s',$value["time"])->format('h:i:s');
print_r($time);
die();
}
The output:
Call to a member function format() on null
What you need is the formatting here:
$dt = Carbon::now();
$dt->toTimeString(); //14:15:16
Carbon\Carbon is an extension to php's DateTime, so you can read at php.net to learn more.
Although America/US is not a valid timezone, so there's something going on with that.
Anyway,
In the database I got: 2018-10-30 01:45:00
If your data type is a TIMESTAMP or a DATETIME, mysql will always have a date component for data in that column.
First, let's get the time out of the $value array to make the rest of the discussion easier to understand and debug:
$time = $value["time"];
From here on out, pay no attention to the internal fields revealed by var_dump. They may or may not actually exist like that in the object. Use the mostly-well-documented interface methods documented in the link above or in the Carbon docs. The fields given by var_dump will just confuse you otherwise.
If you just want the time of day represented as a string, you use the DateTime::format() method:
$timestr = $time->format('H:i:s');
Note that if you insert that string in a database with a DATETIME column type, it won't work. Mysql will require a string that includes date information.
The code snippet that follows doesn't seem to match with the code you show above:
$data = Excel::selectSheetsByIndex(0)->load($path, function($reader) {
})->get()->toArray();
foreach ($data as $key => $value) {
$time = Carbon::createFromFormat('Y-m-d h:i:s',$value["time"])->format('h:i:s');
print_r($time);
}
You are trying to create a Carbon instance using the createFromFormat() method. The first parameter you provide tells Carbon (actually DateTime) what the format of your input string will be. The data you are supplying is H:i:s (assuming $value["time"] is read from the time column of your Excel sheet), but you're telling Carbon that you will be giving it Y-m-d h:i:s. Since the format you promise doesn't match the data you are giving the object, null is resulting.
Either (broken into to steps for clarity):
$time = Carbon::createFromFormat('H:i:s', $value["time"]);
$timestr = $time->format('h:i:s');
or
$time = Carbon::createFromFormat('d-m-Y H:i:s', $value["date"] . " " . $value["time"]);
$timestr = $time->format('h:i:s');
will work.
The second one gives you a Carbon object that is much more useful - the first one will probably default to year zero. In both cases the timezone will be the zone of the machine the code is running on. You can override that if necessary.
Note that if I'm confused and the Excel reader is actually returning Cabon objects rather than strings, you can eliminate the whole createFromFormat code altogether. No sense making a Carbon object out of a Carbon object.
I have been crawling through the web and trying to find a solution so I am coming here.
I have an MSSQL database and I am using PHP5.3 to connect and fetch data from one of the tables. The issue I am having has to do with dates.
$result = sqlsrv_query($conn, "SELECT TOP 10 * FROM TAData WHERE DateTime >= '2013-11-11T07:45:00.000'");
while($row = sqlsrv_fetch_array($result))
{
print_r ($row['DateTime']);
echo "<br />";
echo date("Y-m-d H:i:s", strtotime($row['DateTime']));
}
With the output looking like this:
DateTime Object ( [date] => 2013-11-11 07:46:08 [timezone_type] => 3 [timezone] => Africa/Johannesburg )
January 1, 1970, 2:00 am
All I need is a simple date and time (YYYY-MM-DD HH:MM) that I can use. Once I have it in any sort of format (or understand how it works), I can manipulate it from there. But it is not displaying in any functional way.
You cannot access property date on DateTime object, like in the other answer:
$dt = new DateTime();
echo $dt->date; # this will trigger Notice: Undefined property: DateTime::$date
Please don't use any strtotime() or date() functions, when you already have DateTime object! Just use method format() on DateTime object to format datetime, like:
echo $dt->format('Y-m-d H:i:s');
# or $row['DateTime']->format('Y-m-d H:i:s'); in your example
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/
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
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.
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
How in PHP do I get the regular timestamp format out of a MongoDB date?
Assume I have:
$my_date;
print_r($my_date);
The print_r output is:
MongoDate Object ( [sec] => 1346300336 [usec] => 593000 )
But doing:
echo $my_date;
Outputs:
0.59300000 1346300336
Even tried:
echo (string)$my_date
Same thing.
$my_date->sec is the unix timestamp, use date() function to show it in required format.
echo date('Y-m-d H:i:s', $my_date->sec);
Just a quick update, to say that MongoDate has a toDateTime method since the version 1.6 of the pecl extension.
You can now do
$mongoDate->toDateTime()->format(...)
you are missing the microsecond.
To show (mongo -> php)
$fecha = date(preg_replace('`(?<!\\\\)u`', $my_date->usec, 'Y-M-d H:i:s.u'), $my_date->sec);
//MongoDate ISODate("2013-05-28T15:27:24.735Z")
//Php Date 2013-May-28 10:27:24.735000
To send to mongo (php -> mongo)
$fecha_mongo = new MongoDate(strtotime($fecha));
//Fail function, the short way but, 70000 isn't equal to 700000.
//$fecha_mongo->usec = (int)$fecha_micro->format("u");
preg_match("/\.(.*)/", $fecha, $uSec);
$fecha_mongo->usec = (int)(count($uSec)==2?$uSec[1]:0);
//Php Date 2013-May-28 10:27:24.735000
//MongoDate ISODate("2013-05-28T15:27:24.735Z")
Good day!
Mario T.
First, create date from millisecond using given function:
public function showdatefn($mili)
{
$seconds = (string)$mili / 1000;
return date("d-m-Y", $seconds);
}
$date =$this->showdatefn(<put mongo date here>);
This will give you correct date.
Use MongoDB\BSON\UTCDateTime MongoDate is deprecated
$mongoDate = new \MongoDB\BSON\UTCDateTime(strtotime('2020-10-01 18:30:00'));