I found the solution marked as correct here does not work for me. So, I'm providing my solution that will work. Anyway, before running the code, ensure that mongodb and mongodb php drivers are installed following these two official tutorials:
(1) https://www.mongodb.com/docs/manual/administration/install-community/
(2) https://www.mongodb.com/docs/drivers/php/
Then open your project directory and run the command in terminal/cmd:
composer require mongodb/mongodb
(as mentioned in link no (2) above).
The above command will automatically configure all your dependencies.
After all the above operations are done, run the following
code snippet to create an ObjectId based on timestamp:
<?php
require_once __DIR__ . '/vendor/autoload.php';
// connect to mongodb
$con = new MongoDB\Client("mongodb://localhost:27017");
function createObjectIdFromTimestamp($timeStamp) {
$next_first_4bytes = (string) dechex(rand(1, 65535));
$next_second_4bytes = (string) dechex(rand(1, 65535));
$next_third_4bytes = (string) dechex(rand(1, 65535));
$next_fourth_4bytes = (string) dechex(rand(1, 65535));
$timeStamp = $timeStamp . $next_first_4bytes . $next_second_4bytes . $next_third_4bytes . $next_fourth_4bytes;
$newId = new MongoDB\BSON\ObjectId($timeStamp);
return $newId;
}
// creating a timestamp for 15th March 2013, 03:45:23 am:
$date = date_create_from_format("d-M-Y h:i:s a","15-Mar-2013 03:45:23 am");
// just change the above statement to a date and time you want to create your timestamp for.
/*
To create a date in the format PHP can understand,
the above statement was written. '$date' is a variable
that has stored the date in the format that PHP understands.
In the function: date_create_from_format(),
d = date of the month (in 2 digits), e.g: 15 (in the above statement),
M = name of month (in 3 letters), e.g: Mar (in the above statement),
Y = year (in 4 digits), e.g: 2013 (in the above statement),
h = hour (in 12 hrs format) (in 2 digits), e.g: 03 (in the above statement),
i = minutes (in 2 digits), e.g: 45 (in the above statement),
s = seconds (in 2 digits), e.g. 23 (in the above statement),
a = am or pm, e.g. am (in the above statement)
*/
$timestmp = substr((string) dechex($date -> getTimestamp()), 0, 8);
$id = createObjectIdFromTimestamp($timestmp);
// echo "\$id = " . $id . "<br>";
?>
If you want to create an object id in the current date, then just replace the whole code snippet above with a php statements shown below:
<?php
require_once __DIR__ . '/vendor/autoload.php';
// connect to mongodb
$con = new MongoDB\Client("mongodb://localhost:27017");
$id = new MongoDB\BSON\ObjectId();
?>
I've tested my solution in Ubuntu.