Working datetime between php and mysql - php

I'm just want to check if my way is correct or not. I want to calculate the remaining time for an event.
There are 3 component for it.
The start datetime (in mysql datetime), which is retrieved from mysql.
The duration (minutes in integer), which is also retrieved from mysql.
The current datetime, which is retrieved from php function now().
To count:
The remaining time (in time hh:mm:ss), which is from formula (start + duration) - now
My propose code is:
$row = data->fetch_assoc();
$start = $row["start_time"]; // e.g: "2015-06-19 09:37:16"
$duration = $row["duration"]; // e.g: 60 (minutes)
$now = time(); // e.g: 1434648994
$start_dt = strtotime ($start);
$remaining = ($start_dt + $duration * 60) - $now;
echo "Remaining time: ".$remaining. " seconds."
Is this correct?

Your code now calculates time until the end of the event.
And if $start_dt is lower then $now you get negative value.

Related

How to Add Time with Duration dynamically in PHP?

I am fetching start date and total duration from database. how to add time and duration to calculate total time in php
Below is the data iam getting dynamically.
<?php
$currenttime= date("H:i");
$starttime=$entrance->start_time;
$duration=$entrance->duration;
?>
<?php
$finalstarttime= $starttime + $duration ;
?>
How to get above result.
Time format is H:i
Using the class DateTime it would be something like this:
<?php
$starttime = "16:15";
$duration= "10";
$finalstarttime = (DateTime::createFromFormat("H:i", $starttime))->add(new DateInterval("PT".$duration."M"));
echo $finalstarttime->format("H:i"); // 16:25
where
DateTime::createFromFormat("H:i", $starttime)
creates a DateTime object of the given time-string,
new DateInterval("PT".$duration."M")
creates a DateInterval (in Minutes)
which is added to the starttime via DateTime::add()
$stamp = mktime(16, 15);
$stamp += 60 * 10;
echo date("H:i", $stamp);
OR
$stamp = strtotime("16:15");
$stamp += 60 * 10;
echo date("H:i", $stamp);
Output: 16:25
Use mktime or strtotime to convert your hour and minute to timestamp (which is in seconds), convert your duration in second 10 min * 60 add both of them.
Now get back the final time using date function

Php, add and subtract timestamps, get minutes

I need to get different time lengths in minutes from a few timestamps that are:
starttime
endtime
starttime2nd
endtime2nd
Edit: clarification:
Each time is originally stored as a datetime string, like
"2018-02-21T19:45:13+00:00".
I take that and convert it to strtotime("2018-02-21T19:45:13+00:00");
And from that I get a timestamp : 1519242313
It doesn't seem that I can use plus or minus operators to add or subtract timestamps, like:
$length = ($endtime2nd - $starttime2nd) + ($endtime - $starttime)
Am I required to instantiate DateTime and use the "->diff" method to get a time interval?
I could get one time interval by doing this:
$date1 = new DateTime();
$date2 = new DateTime();
$starttime= $date1->setTimestamp($starttime);
$endtime= $date2->setTimestamp($endtime);
$length = $endtime->diff($starttime);
Does this mean that I need to instantiate four DateTimes to get the total length, and set four timestamps, then get the "->diff" for the two time intervals, and then add them using the "->add" method of DateTime method?
I would just like to know if there is a simpler method?
I don't think you need to instantiate DateTime and use the "->diff" method, because you already have timestamp (as i can see you are using setTimestamp)
<?php
$length = ($endtime2nd - $starttime2nd) + ($endtime - $starttime);
echo round(abs($length / 60), 2). " minute";
?>
You can get the total minuts like this.
$min = $length->d * 24 * 60;
$min = $min + $length->h * 60;
$min = $min + $length->m;

PHP - Deduct two timestamps from each other, display in minutes

I have a mySQL database that stores the checkin and checkout time of a person in a gym. I have imported the checkin and checkout times in to my PHP script. Now I want to deduct the two timestamps from each other - giving me the time left. I want this to display in minutes.
This is my idea:
$checkOut = "2016-01-31 15:01:11";
$checkIn = "2011-01-31 15:32:35";
echo ($checkIn - $checkOut);
// I want this to display 31 minutes.
I have seen many examples on StackOverflow, but none matched my description and I couldn't reverse engineer the ones I found - because they use the time() function - which I guess takes the current time.
You can use strtotime();
$checkOut = "2016-01-31 15:01:11"; // initial value
$checkIn = "2011-01-31 15:32:35"; // initial value
$checkOut_stamp = strtotime($checkOut); // Converting to unix timestamp
$checkIn_stamp = strtotime($checkIn); // Converting to unix timestamp
echo date("i", ($checkIn - $checkOut)) . 'Minute(s)';
IMP Note: The above method will only work if the minutes are below 59, or else the hours will be rounded off and discarded. So if your requirements is showing the time in minutes which can be grater than 59 minutes eg. 144 minutes, then you'd want to just divide by 60, as follows.
$checkOut = "2016-01-31 15:01:11"; // initial value
$checkIn = "2011-01-31 15:32:35"; // initial value
$checkOut_stamp = strtotime($checkOut); // Converting to unix timestamp
$checkIn_stamp = strtotime($checkIn); // Converting to unix timestamp
$seconds = $checkOut_stamp - $checkIn_stamp;
if($seconds > 0){
if($seconds > 60){
$minutes = $seconds/60;
} else {
$minutes = 0;
}
} else {
$minutes = 0;
}
echo $minutes . ' Minute(s)';
$checkOut = "2016-01-31 15:01:11";
$checkIn = "2011-01-31 15:32:35";
$time = (strtotime($checkIn) - strtotime($checkOut));
echo date('i',$time);
use this code
If you were fetching this record from database then you can simply achieve it using MySql function TIMESTAMPDIFF, as no need to use PHP function over here
Select TIMESTAMPDIFF(MINUTE,checkIn,checkout) as tot_diff from your_table

Need a equivalent solution for vbscript command cdbl(now) with php

With vbscript i can retrieve a double value from the current date/time with the command cdbl(now).
Now = '09.05.2015 21:44:10'
cdbl(Now) = 42133,9056712963
I'm looking for a equivalent solution with php that will give me back a double value from the current date/time.
cdbl return datetime in microsoft format. before comma date - number of days since 1 January 1900. After comma time - 24 hours is 1. So if you use dates within Unix epoch (code may be not effective,i wanted make it more understandable)
function cdbl($str) {
$datetime0 = new DateTime('1970-01-01');
$datetime = new DateTime($str);
// 25560 - days from 1 Jan 1900 to 1 Jan 1970
$cdbl = $datetime->diff($datetime0)->days + 25569;
// Remove time from string - it is the sane as 00:00
$str0 = preg_replace('/((T|\s+).+)$/','', $str);
// The number of seconds since the day start
$time = strtotime($str) - strtotime($str0);
// The number of seconds wittin a day
$timefullday = strtotime("$str0 + 1 day") - strtotime($str0);
$cdbl += $time / $timefullday;
return $cdbl;
}
echo cdbl('09.05.2015 21:44:10');
result:
42133.905671296
As you can see, there is a problem of rounding. If print result of the calculation time before summing, the answer will be the same as yours. I've never done calculating tasks, so I can not tell you what to do with it. The only suggestion is convert to a string :)
Well, if you choose to work outside of Unix dates you should write some code
The following function returns the current Unix timestamp as a double value:
function cdblnow(){
// time in seconds since 1 Jan 1970 (GMT)
$timeunix = time();
// add the timezone offset
$TimeZone = "Asia/Bangkok";
$dateTimeZone = new DateTimeZone($TimeZone);
$dateTime = new DateTime("now", $dateTimeZone);
$timeOffset = $dateTimeZone->getOffset($dateTime);
$timeunix = $timeunix + $timeOffset;
// determines the days between 1 Jan 1970 and today
$days = intval($timeunix / 86400);
// second count from today
$secondsremains = $timeunix % 86400;
// 25569 days difference between microsoft and unix time stamp start
$now_date = $days + 25569;
// 0.0000115741 represents one second at the cdbl-function from microsoft
$now_time = $secondsremains * 0.0000115741;
return $now_date + $now_time;}
This function returns the unix time stamp from a double:
function GetUnixTimeFromCdblNow($cdbl){
$days = intval($cdbl);
$seconds = round($cdbl - $days,9);
$timeunix = (($days -25569) * 86400);
$timeunix = $timeunix + intval($seconds / 0.0000115740);
return $timeunix;}

PHP Checking if timestamp is less than 30 minutes old

I'm getting a list of items from my database, each has a CURRENT_TIMESTAMP which i have changed into 'x minutes ago' with the help of timeago. So that's working fine. But the problem is i also want a "NEW" banner on items which are less than 30 minutes old. How can i take the generated timestamp (for example: 2012-07-18 21:11:12) and say if it's less than 30 minutes from the current time, then echo the "NEW" banner on that item.
Use strtotime("-30 minutes") and then see if your row's timestamp is greater than that.
Example:
<?php
if(strtotime($mysql_timestamp) > strtotime("-30 minutes")) {
$this_is_new = true;
}
?>
I'm using strtotime() twice here to get unix timestamps for your mysql date, and then again to get what the timestamp was 30 minutes ago. If the timestamp from 30 mins ago is greater than the timestamp of the mysql record, then it must have been created more than 30 minutes go.
Try something like this, using PHP's DateTime object:
$now = new DateTime();
$then = DateTime($timestamp); // "2012-07-18 21:11:12" for example
$diff = $now->diff($then);
$minutes = ($diff->format('%a') * 1440) + // total days converted to minutes
($diff->format('%h') * 60) + // hours converted to minutes
$diff->format('%i'); // minutes
if ($minutes <= 30) {
echo "NEW";
}
Edit: Mike is right, I forgot that for whatever reason, only %a actually returns the total of its type (in this case days). All the others are for displaying time formatting. I've extended the above to actually work.
You can do like this also -
$currentTime=time();
to check the last updated time is 30 minute old or not
last_updated_at < $currentTime - (60*30)

Categories