Insert ISODate in Mongodb with milliseconds - php

I'm running PHP 7 with the php_mongodb-1.2.2-7.0-nts-vc14-x64 driver.
$ar = new \MongoDB\BSON\UTCDateTime(strtotime('2017-07-27 06:17:25.123000') * 1000);
Output of above statement is:
ISODate("2017-07-27T06:17:25.000+0000")
but I need milliseconds also like:
ISODate("2017-07-27T06:17:25.123+0000")
Since I'm so new I can't seem to figure out how to fix this.

strtotime do not support milliseconds.
strtotime — Parse about any English textual datetime description into
a Unix timesta
So the strtotime('2017-07-27 06:17:25.123000') and strtotime('2017-07-27 06:17:25') will return the same result 1501136245
You must use DateTime:
<?php
$date = DateTime::createFromFormat('Y-m-d H:i:s u', '2017-07-27 06:17:25 123000');
$ar = new \MongoDB\BSON\UTCDateTime($date->format('U.u'));

You can do something like this
function mongo_current_datetime(){
$date = new \MongoDB\BSON\UTCDateTime(strtotime('now') * 1000);
return $date;
}
Example Output:
MongoDB\BSON\UTCDateTime Object
(
[milliseconds] => 1610972571000
)
The function above prepares current datetime Object in milliseconds , ready to insert into mongoDB.

Related

How to correctly add a date and a time (string) in PHP?

What is the "cleanest" way to add a date and a time string in PHP?
Albeit having read that DateTime::add expects a DateInterval, I tried
$date = new \DateTime('17.03.2016');
$time = new \DateTime('20:20');
$result = $date->add($time);
Which was no good and returned nothing to $result.
To make a DateInterval from '20:20', I only found very complex solutions...
Maybe I should use timestamps?
$date = strtotime($datestring);
$timeObj = new \DateTime($timestring);
// quirk to only get time in seconds from string date
$time = $timeObj->format('H') * 3600 + $timeObj->format('i') * 60 + $timeObj->format('s');
$datetime = $date+$time;
$result = new \DateTime;
$result->setTimestamp($datetime);
In my case, this returns the desired result, with the correct timezone offset. But what do you think, is this robust? Is there a better way?
If you want to add 20 hours and 20 minutes to a DateTime:
$date = new \DateTime('17.03.2016');
$date->add($new \DateInterval('PT20H20M'));
You do not need to get the result of add(), calling add() on a DateTime object will change it. The return value of add() is the DateTime object itself so you can chain methods.
See DateInterval::__construct to see how to set the intervals.
DateTime (and DateTimeImmutable) has a modify method which you could leverage to modify the time by adding 20 hours and 20 minutes.
Updated
I've included examples for both DateTime and DateTimeImmutable as per the comment made, you don't need to assign the outcome of modify to a variable because it mutates the original object. Whereas DateTimeImmutable creates a new instance and doesn't mutate the original object.
DateTime
<?php
$start = new DateTimeImmutable('2018-10-23 00:00:00');
echo $start->modify('+20 hours +20 minutes')->format('Y-m-d H:i:s');
// 2018-10-23 20:20:00
Using DateTime: https://3v4l.org/6eon8
DateTimeImmutable
<?php
$start = new DateTimeImmutable('2018-10-23 00:00:00');
$datetime = $start->modify('+20 hours +20 minutes');
var_dump($start->format('Y-m-d H:i:s'));
var_dump($datetime->format('Y-m-d H:i:s'));
Output
string(19) "2018-10-23 00:00:00"
string(19) "2018-10-23 20:20:00"
Using DateTimeImmutable: https://3v4l.org/oRehh

Change seconds duration to ISO 8601 format

How can I convert
00:00:46.70
to
T0M46S
I try
$date = new DateTime($time); echo $date->format('\P\TG\Hi\M');
but it gives me something like this:
PT0H00M
Note I want duration... not date!
There is no native function, but you can do it with native object DateTime : calculate the duration from midnight to your time.
<?php
$time = new DateTime('00:00:46.70');
$midnight = new DateTime('00:00:00.00');
$period = $midnight->diff($time);
echo $period->format('T%iM%SS'); //output T0M46S
print_r($period);
Here is a php sandbox to test it
Carbon has the solution
function secondsToISO8601Format(int $seconds): string
{
return Carbon\CarbonInterval::seconds($seconds)->cascade()->spec();
}

How to return ISO date format in PHP for MongoDB?

I want to store the current date generated from PHP into MongoDB collection as an ISO date formate.
ISODate("2012-11-02T08:40:12.569Z")
However I am not able to generate such Kind of date in php which will be stored in MongoDB as an ISODate format.
This is what I ve done.
$d = new MongoDate(time());
echo $d;
and it is outputting something like,
0.00000000 1353305590
which is not the format I need. How to do this?
You could run the __toString function, or use the sec field
__toString will return a timestamp in usecs, which you can pass to date() after separating the seconds from milliseconds - read here: http://us1.php.net/manual/en/mongodate.tostring.php
OR, I personally prefer to have mongodb return just the seconds, which can be plugged directly into date() - read here: http://php.net/manual/en/class.mongodate.php
Also, if you're generating a MongoDate() for right now, you don't need to specify time();
In order to return an isodate, you need to do this:
echo date(DATE_ISO8601, (new MongoDate())->sec);
...
$exampleDate = new MongoDate();
echo date(DATE_ISO8601, $exampleDate->sec);
EDIT: To save your ISO date, you need to do the following:
$mongoDateObject = new MongoDate(strtotime("2012-11-02T08:40:12.569Z"));
For clarity, let's consider the following use case:
You need to convert a string in the simplified extended ISO 8601 format (e.g. returned by Javascript's Date.prototype.toISOString()) to and from PHP's MongoDate object, while preserving maximum precision during conversion.
In this format, the string is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ. The timezone is always zero UTC offset, as denoted by the suffix Z.
To keep milliseconds, we'll have to leverage PHP's DateTime object.
From string to MongoDate:
$stringDt = "2015-10-07T14:28:41.545Z";
Method 1 (using date_create_from_format):
$phpDt = date_create_from_format('Y-m-d\TH:i:s.uP', $stringDt);
$MongoDt = new \MongoDate($phpDt->getTimestamp(), $phpDt->format('u'));
Method 2 (using strtotime):
$MongoDt= new \MongoDate(strtotime ($stringDt),
1000*intval(substr($stringDt, -4, 3)) // cut msec portion, convert msec to usec
);
From MongoDate to string:
$MongoDt = new \MongoDate(); // let's take now for example
$stringDt =
substr(
(new \DateTime())
->setTimestamp($MongoDt->sec)
->setTimeZone(new \DateTimeZone('UTC'))
->format(\DateTime::ISO8601),
0, -5) // taking the beginning of DateTime::ISO8601-formatted string
.sprintf('.%03dZ', $MongoDt->usec / 1000); // adding msec portion, converting usec to msec
Hope this helps.
convert ISO date time in UTC date time here :
$timestamp = $quicky_created_date->__toString(); //ISO DATE Return form mongo database
$utcdatetime = new MongoDB\BSON\UTCDateTime($timestamp);
$datetime = $utcdatetime->toDateTime();
$time=$datetime->format(DATE_RSS);
$dateInUTC=$time;
$time = strtotime($dateInUTC.' UTC');
$dateInLocal = date("d M Y", $time);
echo $dateInLocal; die;
You can convert ISODate time by using below code.
* return ISO-8601 date format:YYYY-MM-DD'T'HH:mm:ss.sssXXX , for example: 2015-09-07T10:13:45.110-07:00 .
*/
date("Y-m-d\TH:i:s.000P", strtotime($date));

Printing A MongoDB Date From 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'));

Converting date to this format

I have a date in this format:
24-12-2010 // DAY - MONTH - YEAR
I need to get it in this format:
1995-12-31T23:59:59.999Z // The Z is for the TimeZone I think.
Check this link out:
http://lucene.apache.org/solr/api/org/apache/solr/schema/DateField.html
The above link is the way I need the date.
I am using PHP now, so this needs to be with PHP.
How can I convert these dates the easiest way?
Thanks
That is an ISO8601 format date; the following is what you want.
gmdate('Y-m-d\TH:i:s\Z', strtotime($date_value));
You can do something like that:
$dateTime = new DateTime($myDate);
$formatted = $dateTime->format("Y-m-d\TH:i:s.z\Z");
The mentioned solution with:
$dateTime->format(DateTime::W3C);
$dateTime->format(DateTime::ISO8601);
does return strings like:
2012-11-28T17:21:11+0100
which cannot be parsed, at least with newer Solr versions.
I wouldn't use gmdate if you need to support timezones. The DateTime implementation is well done, and is also available for functional programming.
http://php.net/manual/en/class.datetime.php
http://php.net/manual/en/ref.datetime.php
You can use the DateTime class
$dateTime = new DateTime();
$dateTime.setDate(24, 12, 2010);
$output = $dateTime.format(DateTime::W3C);
// Output now is your date in W3C format.
use the date ( string $format [, int $timestamp ] ) function of php!
In second paramter use http://php.net/manual/en/function.strtotime.php to get the timestamp from strings
$date = strtotime('24-12-2010');
$new_date = gmDate("Y-m-d\TH:i:s.z\Z",$date);

Categories