Add two times of different format in PHP - php

In my table, I have a variable $duration which is stored in minutes.
And I also have a time variable. Let it be $time1.
$time1=date('H:i:s',$time);
$duration=1000; //minutes
$time2= secondsToTime($duration*60);
I convert the $duration to time format using the function given below.
function secondsToTime($seconds) {
$dtF = new DateTime("#0");
$dtT = new DateTime("#$seconds");
return $dtF->diff($dtT)->format('%h:%i:%s');
}
So in $time2, i have something like this stored 11:12:13
And in $time1 i have something like this stored 01:10:19
I want to perform $total=$time1+$time2;
So, I converted $time2 into time format.
$timeform= new DateTime($time2);
$newtime2= $timeform->format('H:i:s');
Now, I add $total=$time1+$newtime2;
But echo date('H:i:s',$total);gave me following error:
Notice: Object of class DateTime could not be converted to int

The second argument of date() should be a timestamp (i.e. an integer, i.e. seconds), not a formatted date string.
As far as I know only comparison operators work on datetime objects ($date1 > $date2), not math operators ($date1 + $date2).
See also http://nl3.php.net/manual/en/datetime.add.php and http://nl3.php.net/manual/en/datetime.modify.php
Use 1 datetime instance for calculating/formatting the total amount of time
Or, convert 2 datetime instances to seconds, add them, and format using date()

The second parameter of date() is expected to be a Unix timestamp as integer, not a DateTime object. (see php.net)
You need to convert your DateTime object into a Unix timestamp.
Try getTimestamp():
echo date('H:i:s',$total->getTimestamp());

Related

Find Current Time and Subtract Previous Time in Seconds

I'm trying to find the current date and time, convert to a unix timestamp, and then subtract a previous time. I've tried multiple approaches and have received errors or incorrect values. So far here is my code:
// Current date and time
$currentTime = date("Y-m-d H:i:s");
// Convert datetime to Unix timestamp
$currentTimestamp = strtotime($currentTime);
// Create previous date and time
$previousTime = new DateTime("2021-04-17 13:00:00");
// Specify display format
$previousTime->format('Y-m-d H:i:s');
// Convert to Unix timestamp
$previousTimestamp = strtotime($previousTime);
// Subtract previous time from current time
$time = $currentTimestamp - $previousTimestamp;
// Display result
echo $time;
So how it should work is if the current date and time is for example: 2021-04-17 14:00:00 and the previous date and time is 2021-04-17 13:00:00, then the result should be 3600. Or if there is a two hour gap, then it's 7200, etc. With this current code, the error I'm getting is:
Uncaught TypeError: strtotime(): Argument #1 ($datetime) must be of
type string, DateTime
And other code I have tried doesn't return the correct time difference or other errors are thrown. How do I get the correct time difference?
You need to read the docs about what each function expects as an argument and what each returns. You're mixing a timestamp (an integer) with a DateTime object. If you want to do date calculations, you'll need to use the same format for both. Since you're looking for the number of seconds difference, it's probably simpler to use timestamp integers.
This code gives you an integer timestamp:
$currentTime = date("Y-m-d H:i:s");
$currentTimestamp = strtotime($currentTime);
But note that "now" is the default return value for the time() function, so you can just do this instead:
$currentTimestamp = time();
And you don't need this:
// This gives you a DateTime object
$previousTime = new DateTime("2021-04-17 13:00:00");
// This doesn't change the internal representation,
// it just returns a value that you're not using.
$previousTime->format('Y-m-d H:i:s');
// This function expects a string, but you're giving an object.
$previousTimestamp = strtotime($previousTime);
Instead, you can just pass your formatted date string directly to strtotime() and it will return an integer timestamp:
$previousTimestamp = strtotime("2021-04-17 13:00:00");
Now you have two integers representing seconds, so you can just subtract them to get the number of seconds between. Your prog becomes:
$currentTimestamp = time();
$previousTimestamp = strtotime("2021-04-17 13:00:00");
$diff = $currentTimestamp - $previousTimestamp;
echo $diff;
Or just:
echo time() - strtotime("2021-04-17 13:00:00");

DateTime Comparison with objects php

This may be the most simple question however i don't know to best aproach this
I have 2 dates to compare $lp & now()
$lp = $ur->getLastPost($usr) ?: new \DateTime('yesterday');
$tdiff = date_diff(strtotime($lp),strtotime('now'));
$lp can either be 2019-11-21 17:20:44 or an current yesterday time
I want to transform $lp in a unixtimestamp so I can see if the difference is bigger than 3600 seconds
My problem is that i can't use strtotime because $lp can be an object, hence the error strtotime() expects parameter 1 to be string, object given
You must parse datetime to format of you $lp:
$date = new DateTime($ur->getLastPost($usr) ?: 'yesterday');
$date->format('Y-m-d H:i:s');
then you can use date_diff to get difference of dates.
print_r($date->diff(new \DateTime('now')));
see DateTime::diff and Datetime class

Maximum int value result function time()

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!

subtract and add a variable of time to a given time using php

I have a given time and i need to create another time base on another given time. Let suppose i have given 4:00:00 AM, and another time is 2:00:00 , my result should be 6:00:00 AM, and 2:00:00 AM(based on condition).
this is what i am using but its not giving correect result.
if($data['turn_on_before_or_after'] == 'before'){
$time = strtotime($data['sunset']) - strtotime($data['variation_turn_on']);
$dataNew['final_turn_on'] = date('h:m:s',$time);
}
if($data['turn_on_before_or_after'] == 'after'){
$time = strtotime($data['sunset']) + strtotime($data['variation_turn_on']);
$dataNew['final_turn_on'] = date('h:m:s',$time);
}
Recommendation: use strtotime(). It will takes the date/time/datetime string and convert it to an integer; starting at the unix epoch. So 2AM would be 7200 and 4AM would be 14400; add those integers together and use date('H', $result) would convert the integer back into a time string. Boosh, win!
Opinion: many people will say unix timestamp is hard to use 'cause it is not human readable;I'd rather my logic be easy to read than the output. As the output only happens at the end of processing.
I recreated your scenario, but instead of using strtotime I used the DateTime object.
Your main problem is that your first date ($data['sunset']) must be considered as a real date, but your second date ($data['variation_turn_on']) must be considered as an interval. Because of this, and after looking at the DateInterval object constructor, you notice that you can create an interval using sscanf from your initial string. After creating that interval, all you have to do is to use the methods from the DateTime class to simply add or substract intervals from a specific date.
Here is the code I wrote to obtain the results you expect (6:00:00 AM and 2:00:00 AM) :
<?php
/* Initial parameters */
$data['turn_on_before_or_after'] = "before";
$data['sunset'] = "4:00:00 AM";
$data['variation_turn_on'] = "2:00:00";
/* Creating a list with your variation values */
list($hours, $minutes, $seconds) = sscanf($data['variation_turn_on'], '%d:%d:%d');
/* Creating the interval (here is the magic) */
$intervale = new DateInterval(sprintf('PT%dH%dM%dS', $hours, $minutes, $seconds));
/* Creating a DateTime object from your sunset time */
$date = new DateTime($data['sunset']);
/* Ternary for simplification, substract if before, add if everything else, you may use an if statement here */
$data['turn_on_before_or_after'] == 'before' ? $date->sub($intervale) : $date->add($intervale);
/* Printing the result */
echo $date->format('h:i:s A');

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

Categories