Hello guys I 'm storing date in mongodb. The problem that I'm facing is that the date time string that I get. I try to convert it into mongodate but it converts it to 0.00000000 2016. Here is the code
$params['start'] = new MongoDate($params['start']);
$params['end'] = new MongoDate($params['end']);
The string bring the date time in this form 2016-04-07 19:49:50 but after the conversion it becomes like this 0.00000000 2016. Please tell me what is it that I'm doing wrong
Per the docs, MongoDate expects a timestamp value like 1460058590, not a string like 2016-04-07 19:49:50.
$params['start'] = new MongoDate(strtotime($params['start']));
The MongoDate constructor expects the time in Unix epoch seconds, not a time string.
public MongoDate::__construct ([ int $sec = time() [, int $usec = 0 ]] )
You'll need to convert your time string using strtotime or DateTime. The example code from the constructor documentation even includes an example:
$d = new MongoDate(strtotime("2009-05-01 00:00:01"));
echo "$d\n";
Related
I need to save the value returned by the php "time();" function in a mysql table.
When I create an int field within a table, the maximum length of the int value is requested.
I wanted to ask you what value suggest to include in the type declaration of int.
I ask you this because, by saving the digit in int, it will be easy to compare it with other results of the "time ();" (which if I understand correctly, it always returns an int value).
Thank you
As of PHP manual:
Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
So you're better of with using DATETIME type in your MySQL database and saving the timestamp after you convert it into valid format. For that I'd use DateTime. Even better if you just use new DateTime instead of time(), as DateTime takes time in constructor, which by default is now:
public DateTime::__construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
If you were to use Doctrine 2, it would have been enough. Otherwise, you must format your DateTime object before inserting:
$dt = new DateTime();
$dt->format('Y-m-d H:i:s');
This will produce something like
2019-04-30 15:34:16
which is completely valid format for your DATETIME type in your mysql database.
If you need to compare other DateTime objects, you can always use DateTime::diff:
public DateTime::diff ( DateTimeInterface $datetime2 [, bool $absolute = FALSE ] ) : DateInterval
This will be enough for smart and representable operations with DateTimes and their comparison.
EDIT:
As you wrote
Ok, I converted the db field into a "DATETIME" field. But now I can't compare the result of the table field with a DateTime () object. Do you know how I can convert the table field to be comparable with a DateTime () object?
You need to create the DateTime object from the data you have in your database. It is achieved by using createFromFormat:
public static DateTime::createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] ) : DateTime
So what you do is:
$dt = DateTime::createFromFormat('Y-m-d H:i:s', '2019-04-30 15:34:16');
and voila!
I am using DateTime function of php. I get a date from a calendar in format d-m-Y and pass it via ajax to my function. I am getting the date right till this step.
When I try to store the date in unix format using:
$ai_ff_date=DateTime::CreateFromFormat('d-m-Y', $data['date']);
$final_date=$ai_ff_date->format('U');
The date stored is wrong. Suppose the date I passed via ajax is 26-12-2016 then in database 27-12-2016 is stored. Why its counting one more day then the input.
use this code :
$date = date('Y-m-d H:i:s', strtotime('-1 day', $stop_date));
$ai_ff_date=DateTime::CreateFromFormat('d-m-Y',$date);
$final_date=$ai_ff_date->format('U');
and please check the variable (code not tested)
You might want to convert the Date-Format to "Y-m-d" First and then call-in the DateTime() Constructor. However, since what you are trying to do is just get the TimeStamp you might also do that directly without using DateTime. The Snippet below shows what is meant here:
<?php
$data = ['date'=>"13-12-2016"]; //<== JUST AN EXAMPLE FOR TESTING!!!
// SIMPLY CONVERT THE DATE TO Y-m-d FIRST.
$dateYMD = date("Y-m-d", strtotime($data['date']));
// THEN USE DateTime CONSTRUCTOR TO CREATE A NEW DateTime INSTANCE
// AND THEN RUN THE FORMAT YOU WISH::
$final_date = (new DateTime($dateYMD))->format('U');
var_dump($final_date); //<== YIELDS: string '1481583600' (length=10)
var_dump(date("Y-m-d", $final_date)); //<== YIELDS: string '2016-12-13' (length=10)
I want to convert the string 1433669892 to 07-06-2015 (June, 7th, 2015).
For that, I'm using the code:
$date = date('d-m-Y',strtotime ($row['order_created']));
Where:
$row['order_created']= '1433669892'
Which is returning:
31-12-1969
Totally different of what I expected. I know this should be trivial, but I can't manage to get the right date.
Try this:
$date = date('d-m-Y', intval( $row['order_created'] ) );
The timestamp passed to the function date() should be an integer as you seem to have in your row.
Edit Casting to an integer
Suppose I have an offset like this:
$secOffset = -28800
I need it to convert in a format that is usable with MYSQL function convert_tz()
If I use gmdate("h:i", secOffset) I got 16:00 that is almost correct but It miss the minus - (that is quite important)
Alternative approach:
Suppose I have a time string America/Los_Angeles and I want to convert in a offset useful for MYSQL function convert_tz()
The final expected output is the offset from GMT so given a timezone.
For ex, having a timezone like America/Los_Angeles, the output should be:
−08:00
I'm on Magento/Zend so if any available function is on Zend I can accept answer based on it.
You should use the DateTimeZone and DateInterval classes for this:
$tzid = 'America/Los_Angeles';
$tz = new DateTimeZone($tzid);
$date = new DateTime('now', $tz);
// create a new date offset by the timezone offset
// gets the interval as hours & minutes
$offset = $tz->getOffset($date) . ' seconds';
$dateOffset = clone $date;
$dateOffset->sub(DateInterval::createFromDateString($offset));
$interval = $dateOffset->diff($date);
$formatted = $interval->format('%R%H:%I');
This is a little convoluted, as you first get the timezone offset in seconds, and then use DateTime to help convert that interval into hours/mins.
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));