Search code examples
phpphp-mongodb

How get previous date from today in mongodb php?


I am extracting today's date using below code and put that value in $today

$today =  new MongoDB\BSON\UTCDateTime((new DateTime())->getTimestamp() * 1000);
var_dump($today);

The output is

object(MongoDB\BSON\UTCDateTime)#10 (1) { ["milliseconds"]=> string(13) "1535621796000" }

Now I want to extract one day before today's date and put that value in yesterday in "ISODate("2018-08-29T22:00:00.0Z")" format.


Solution

  • strtotime(date("Y-m-d H:i:s",$today->toDateTime()->getTimeStamp()).' -1 day') should do according to http://php.net/manual/en/mongodb-bson-utcdatetime.todatetime.php and http://php.net/manual/en/class.datetime.php

    Once you have timestamp of yesterday you can format the result with date(format,timestamp) or whatever other class you prefer