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

Related

How to convert T-Z string to australian time? [duplicate]

So I've checked the list of supported time zones in PHP and I was wondering how could I include them in the date() function?
Thanks!
I don't want a default timezone, each user has their timezone stored in the database, I take that timezone of the user and use it. How? I know how to take it from the database, not how to use it, though.
For such task, you should really be using PHP's DateTime class. Please ignore all of the answers advising you to use date() or date_set_time_zone, it's simply bad and outdated.
I'll use pseudocode to demonstrate, so try to adjust the code to suit your needs.
Assuming that variable $tz contains string name of a valid time zone and variable $timestamp contains the timestamp you wish to format according to time zone, the code would look like this:
$tz = 'Europe/London';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
echo $dt->format('d.m.Y, H:i:s');
DateTime class is powerful, and to grasp all of its capabilities - you should devote some of your time reading about it at php.net. To answer your question fully - yes, you can adjust the time zone parameter dynamically (on each iteration while reading from db, you can create a new DateTimeZone() object).
If I understood correct,You need to set time zone first like:
date_default_timezone_set('UTC');
And than you can use date function:
// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
The answer above caused me to jump through some hoops/gotchas, so just posting the cleaner code that worked for me:
$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('America/New_York'));
$dt->setTimestamp(123456789);
echo $dt->format('F j, Y # G:i');
Use the DateTime class instead, as it supports timezones. The DateTime equivalent of date() is DateTime::format.
An extremely helpful wrapper for DateTime is Carbon - definitely give it a look.
You'll want to store in the database as UTC and convert on the application level.
It should like this:
date_default_timezone_set('America/New_York');
U can just add, timezone difference to unix timestamp.
Example for Moscow (UTC+3)
echo date('d.m.Y H:i:s', time() + 3 * 60 * 60);
Try this. You can pass either unix timestamp, or datetime string
public static function convertToTimezone($timestamp, $fromTimezone, $toTimezone, $format='Y-m-d H:i:s')
{
$datetime = is_numeric($timestamp) ?
DateTime::createFromFormat ('U' , $timestamp, new DateTimeZone($fromTimezone)) :
new DateTime($timestamp, new DateTimeZone($fromTimezone));
$datetime->setTimezone(new DateTimeZone($toTimezone));
return $datetime->format($format);
}
this works perfectly in 2019:
date('Y-m-d H:i:s',strtotime($date. ' '.$timezone));
I have created this very straightforward function, and it works like a charm:
function ts2time($timestamp,$timezone){ /* input: 1518404518,America/Los_Angeles */
$date = new DateTime(date("d F Y H:i:s",$timestamp));
$date->setTimezone(new DateTimeZone($timezone));
$rt=$date->format('M d, Y h:i:s a'); /* output: Feb 11, 2018 7:01:58 pm */
return $rt;
}
I have tried the answers based on the DateTime class. While they are working, I found a much simpler solution that makes a DateTime object timezone aware at the time of creation.
$dt = new DateTime("now", new DateTimeZone('Asia/Jakarta'));
echo $dt->format("Y-m-d H:i:s");
This returns the current local time in Jakarta, Indonesia.
Not mentioned above. You could also crate a DateTime object by providing a timestamp as string in the constructor with a leading # sign.
$dt = new DateTime('#123456789');
$dt->setTimezone(new DateTimeZone('America/New_York'));
echo $dt->format('F j, Y - G:i');
See the documentation about compound formats:
https://www.php.net/manual/en/datetime.formats.compound.php
Based on other answers I built a one-liner, where I suppose you need current date time. It's easy to adjust if you need a different timestamp.
$dt = (new DateTime("now", new DateTimeZone('Europe/Rome')))->format('d-m-Y_His');
If you use Team EJ's answer, using T in the format string for DateTime will display a three-letter abbreviation, but you can get the long name of the timezone like this:
$date = new DateTime('2/3/2022 02:11:17');
$date->setTimezone(new DateTimeZone('America/Chicago'));
echo "\n" . $date->format('Y-m-d h:i:s T');
/* Displays 2022-02-03 02:11:17 CST "; */
$t = $date->getTimezone();
echo "\nTimezone: " . $t->getName();
/* Displays Timezone: America/Chicago */
$now = new DateTime();
$now->format('d-m-Y H:i:s T')
Will output:
29-12-2021 12:38:15 UTC
I had a weird problem on a hosting. The timezone was set correctly, when I checked it with the following code.
echo ini_get('date.timezone');
However, the time it returned was UTC.
The solution was using the following code since the timezone was set correctly in the PHP configuration.
date_default_timezone_set(ini_get('date.timezone'));
You can replace database value in date_default_timezone_set function,
date_default_timezone_set(SOME_PHP_VARIABLE);
but just needs to take care of exact values relevant to the timezones.

Insert ISODate in Mongodb with milliseconds

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.

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));

How can I check if the current date/time is past a set date/time?

I'm trying to write a script that will check if the current date/time is past the 05/15/2010 at 4PM
How can I use PHP's date() function to perform this check?
Since PHP >= 5.2.2 you can use the DateTime class as such:
if (new DateTime() > new DateTime("2010-05-15 16:00:00")) {
# current time is greater than 2010-05-15 16:00:00
# in other words, 2010-05-15 16:00:00 has passed
}
The string passed to the DateTime constructor is parsed according to these rules.
Note that it is also possible to use time and strtotime functions. See original answer.
There's also the DateTime class which implements a function for comparison operators.
// $now = new DateTime();
$dtA = new DateTime('05/14/2010 3:00PM');
$dtB = new DateTime('05/14/2010 4:00PM');
if ( $dtA > $dtB ) {
echo 'dtA > dtB';
}
else {
echo 'dtA <= dtB';
}
Check PHP's strtotime-function to convert your set date/time to a timestamp: http://php.net/manual/en/function.strtotime.php
If strtotime can't handle your date/time format correctly ("4:00PM" will probably work but not "at 4PM"), you'll need to use string-functions, e.g. substr to parse/correct your format and retrieve your timestamp through another function, e.g. mktime.
Then compare the resulting timestamp with the current date/time (if ($calulated_timestamp > time()) { /* date in the future */ }) to see whether the set date/time is in the past or the future.
I suggest to read the PHP-doc on date/time-functions and get back here with some of your source-code once you get stuck.
date_default_timezone_set('Asia/Kolkata');
$curDateTime = date("Y-m-d H:i:s");
$myDate = date("Y-m-d H:i:s", strtotime("2018-06-26 16:15:33"));
if($myDate < $curDateTime){
echo "active";exit;
}else{
echo "inactive";exit;
}

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