I have a MySQL DB with StartDates in the format of yyyy-mm-dd and starttimes in the format of HH:MM using a 24 hour clock. What would be the easiest way to compare the difference of two days in PHP? Would using a datetime object could I set it to be with the information given and just give it to zeros for the seconds? I need to get the amount of time between both dates down to the minute. I was putting the startdate (Just the day since its always within the same month for my application) and time together concatenated together and then pulling out what I need like below, but I haven't been able to get it straight yet. Thanks for the look!
$tempvar1 = $times[$i][$j];
$tempvar2 = $times[$i][$j+1];
$day1 = $tempvar1[0].$tempvar1[1];
$day2 = $tempvar2[0].$tempvar2[1];
$hours1 = $tempvar1[2].$tempvar1[3];
$hours2 = $tempvar2[2].$tempvar2[3];
$minutes1 = $tempvar1[5].$tempvar1[6];
$minutes2 = $tempvar2[5].$tempvar2[6];
$numdays = ($day2-$day1) - 1;
$time1 = ($hours1*60)+$minutes1;
$time2 = ($hours2*60)+$minutes2;
MySQL has plenty of date/time functions:
SELECT TIMEDIFF(endtime, starttime), DATEDIFF(endtime, starttime)
FROM ...
doc links for timediff and datediff
That'll you get strings in the format of 'hh:mm:ss.ssss' for timediff, and a straight-up integer representing the days between the two dates, respectively.
Related
Suppose I have a time string '9:30' which I want to convert to timestamp.
What I do right now is extracting it and manually calculate the timestamp.
list($hour, $minute) = explode(':', '9:30');
$timestamp = $hour * 3600 + $minute * 60;
I'm wondering whether there is a smart way using Carbon or DateTime object.
use strtotime()
manual
$time = '9:30';
$timestamp = strtotime($time);
echo date('H:i',$timestamp);
I don't think you'll be able to get a timestamp from only hour or minute, as timestamp is number of seconds from 00:00:00 Thursday 1 January 1970 (check wikipedia link for more details). So without the date part you can't have a timestamp. Could you please explain how you're planning to use this?
If you're planning to calculate a different timestamp from a given datetime, then you can just do it differently. Say you're planning to get the timestamp 1 day or 24 hours after given time, then you can do it like this (non object oriented way):
$givenTimestamp = strtotime('17-06-2018 09:30:00');
$dayInSeconds = 24*60*60;
$calculatedTimeStamp = $givenTimestamp + $dayInSeconds;
If you're just trying to get how many seconds has been passed for the time section of the timestamp (like 9:30 in your example for a given day), then you can just do it like this:
list($hour, $minute) = explode(':', date ('H:i', strtotime('2018-06-16 09:30:00')));
$secondsSinceStartOfDay = intval($hour)*60*60 + intval($minute) * 60;
You may get the same result without using the intval on $hour and $minute, but it would be better to use intval on them to avoid possible issues in some cases.
Update with Carbon
From Carbon documentation, it seems like you still need the date part to generate the timestamp. So if you have your $date like this '2018-06-16' and $time like this '09:30', then you can recreate your datetime like this:
$dateTimeString = $date .' '. $time .':00';
$carbonDateTime = Carbon::parse($dateTimeString);
// $carbonDateTime will now have your date time reference
// you can now get the timestamp like this
echo $carbonDateTime->timestamp;
I'm really not grasping how dates and times get formatted in PHP for use in mathematical equations. My goal is this;
Get a date and time from the database;
// Get array for times in
$sth = mysqli_query($conn,"SELECT * FROM ledger ORDER BY ID");
$timeins = array();
while($r = mysqli_fetch_assoc($sth)) {
$timeins[] = $r["timein"];
//OR
array_push($timeins, $r['timein']);
}
And then find the distance between the current time and the variable in the array, $timeins[0], and then put the minutes, hours, and days difference in separate simple variables for later use. These variables will be used on their own in if statements to find out if the person has passed certain amounts of time.
edit: the format of the dates being returned from the DB is in the default TIMESTAMP format for MySQL. E.g. 2018-08-06 17:38:37.
It is also possible to perform datetime operations in SQL, to get a difference between two datetime/timestamp values in days, hours, minutes... We can use expressions in the SELECT list, to return the results as columns in the resultset.
Ditching the SELECT * pattern, and specifying an explicit list of expressions that we need returned:
$sql = "
SELECT t.id
, t.timein
, TIMESTAMPDIFF(DAY ,t.timein,NOW()) AS diff_days
, TIMESTAMPDIFF(HOUR ,t.timein,NOW()) AS diff_hours
, TIMESTAMPDIFF(MINUTE ,t.timein,NOW()) AS diff_minute
FROM ledger t
ORDER BY t.id ";
if( $sth = mysqli_query($conn,$sql) ) {
// execution successful
...
} else {
// handle sql error
}
You should use the DateTime class in PHP to do any date manipulation. You can convert a string representation of a MySQL format time to a PHP DateTime object using
$date = DateTime::createFromFormat('Y-m-d H:i:s', $mysqldate);
Also you can create a DateTime object representing the current time using the constructor with no argument:
$now = new DateTime();
To get the difference between two dates as a DateInterval object, use the builtin diff method:
$diff = $now->diff($date);
As a complete example:
$now = new DateTime();
$mysqldate = '2018-04-03 12:30:01';
$date = DateTime::createFromFormat('Y-m-d H:i:s', $mysqldate);
$diff = $now->diff($date);
$diff_days = (int)$diff->format('%a');
$diff_hours = $diff->h;
$diff_minutes = $diff->m;
echo "$diff_days days, $diff_hours hours, $diff_minutes minutes";
Output:
125 days, 9 hours, 4 minutes
Note that you have to use $diff->format('%a') rather than $diff->d to get the days between two dates, as $diff->d will not include the days in any months between the two dates (in this example it will return 3 for today being August 6).
Using the DateTime Class in php is the best way to get accurate results.
$dateNow = new DateTime('now');
$dateIn = DateTime::createFromFormat('d-m-Y H:i:s', $timeins[0]);
$interval = $dateNow->diff($dateIn);
echo $interval->format('%d days, %h hours, %i minutes, %s seconds');
$deltaDays = $interval->d;
$deltaHours = $interval->h;
...
You have to make sure the input format for you DB date is correct, in this case, I assumed d-m-y H:i:s, and then you can output in any format you need as well, as shown in the date docs: http://php.net/manual/en/function.date.php
I have a user defined formula stored in a database table as string "({Arrival_Date}-{Departure_Date})". I then have below rows selected from a table.
Departure_Date Arrival_Date
2015-01-01 2015-03-01
2015-02-01 2015-02-10
I want to use formula ({Arrival_Date}-{Departure_Date}) and get the difference in days i.e (2015-03-01 - 2015-01-01) = 2 etc for all rows. Any suggestions on how i can match value with my formula?
Thank you in-advance.
Once you have stored the two dates in two variables, you can try this:
<?php
$str1 = '2015-01-01';
$str2 = '2015-03-01';
$datetime1 = new DateTime($str1);
$datetime2 = new DateTime($str2 );
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>
BTW I don't know which format the DateTime accepts (YYYY-MM-DD or YYYY-DD-MM) or if it depends on the server's international options.. If it doesn't work properly you can use DateTime::createFromFormat to manually specify the fields.
EDIT:
I don't know much about curly braces templates, but if you want to get the result as a difference, you can convert the DateTime object in its timestamp representation:
$datetime1 = new DateTime($str1);
$datetimeTS1 = $datetime1->getTimestamp();
// Or, alternatively, you can use
$datetimeTS1 = $datetime1->format("U");
The two options should be the same for dates after January 1, 1970.
The two variables $datetimeTS1 and $datetimeTS2 are now two integers. Their difference is the difference between the two dates expressed in seconds (since there are 86400 seconds in a day, you will now just have to divide the result by 86400). You can also write
$datetimeTS1 = $datetime1->getTimestamp() / 86400;
$datetimeTS2 = $datetime2->getTimestamp() / 86400;
because the two dates do not have "half days".
I have stored date field at DB.
In PHP, i am getting that field and converted into date.
I want to compare that time with current time. If that difference is above 60 minutes. It will return some value.
I dont know how to write logic for that
$lastUpdatedField = $rows_fetch['lastUpdatedTime'];
$lastUpdatedDate = new DateTime($lastUpdatedField);
$nowDate = new DateTime(date('y-m-d h:m:s'));
I have old date&time is in $lastUpdatedDate variable, and current time is in $nowDate.
How to compare these two
$interval = $nowDate->diff($lastUpdatedDate);
echo $interval->h;
DateDiff: http://www.php.net/manual/en/datetime.diff.php
DateInterval: http://www.php.net/manual/en/class.dateinterval.php
Had The same problem earlier its actually quit simple
heres the piece where you declare your variables
$lastUpdateddate = new DateTime($lastUpdatedField);
$nowDate = new DateTime(date('y-m-d h:m:s'));
Then you have to convert them to second - format so that you can do math with them
To do that use strtotime
$Diff = strtotime($lastUpdatedDate) - strtotime($nowDate);
Then just check to see if the difference in time is more then 60 minutes,
So devide by 60 seconds to get minutes and by 60 to get hours
if ($diff/60/60 <= 1){
//do your thing here
{
First convert the current time and old time to one unit like Unix timestamp passing it through strtotime(). Then differentiate both the timestamp to get the difference between two times.
$difftime = strtotime(date('Y-m-d H:i:s')) - strtotime($rows_fetch['lastUpdatedTime']);
Then convert the difference to days as follows :
$days=$difftime/24*60*60;
Once you get the days you can get the minutes from it as below to compare to meet your need.
$timediff = $days * 24 * 60;
How can I compute time difference in PHP?
example: 2:00 and 3:30.
I want to convert the time to seconds then subtract them then convert it back to hours and minutes to know the difference. Is there an easier way to get the difference?
Look at the PHP DateTime object.
$dateA = new DateTime('2:00');
$dateB = new DateTime('3:00');
$difference = $dateA->diff($dateB);
(assuming you have >= PHP 5.3)
You can also do it the procedural way...
$dateA = strtotime('2:00');
$dateB = strtotime('3:00');
$difference = $dateB - $dateA;
See it on CodePad.org.
You can get the hour offset like so...
$hours = $difference / 3600;
If you are dealing with times that fall between a 24 hour period (0:00 - 23:59), you could also do...
$hours = (int) date('g', $difference);
Though that is probably too inflexible to be worth implementing.
Check this link ...
http://www.onlineconversion.com/days_between_advanced.htm
I used this to calculate the difference between server time and the users local time. Grab the hour difference and drop that in a form when the user is registering. I then use it to update the time on the site for the user when they do stuff online.
Once I got it working, I switched this line ...
if (form.date1.value == "")
form.date1.value = s;
to ...
form.date1.value = "<?PHP echo date("m/d/Y H:i:s", time()) ?>";
Now I can compare the user time and the server time! You can grab the seconds and mins as well.