how to calculate 2 hours from the time request made in seconds - php

My server time is GMT, so I convert it to Asia/Kuala Lumpur timing.I need to calculate time difference between current time and the time request was made. The time request was made is stored in database and retrieved in $reset_req variable.
$reset_req="2015-06-30 11:30:23";
$timezone_offset = +8; // us central time (gmt-6) for me
if(isset($reset_req)){
$request_date2 = strtotime($reset_req)+$timezone_offset*60*60;
}
echo "current time= ".strtotime(time());
echo"<br/>";
echo "time req made=".strtotime($request_date2);
echo"<br/>";
$timediff = strtotime(time()) - strtotime($request_date2); // in seconds
if($timediff < 2 hours)//how to calculate 2 hours here
{
//do something
}

Everyone already said how to calculate 2 hours (2* 3600sec). But what they didn't tell you is that you can't do this: strtotime(time()); time(); already gives you a Unix timestamp so you can't convert it twice.
Your Code should look more like this
<?php
$reset_req = "2015-06-30 11:30:23";
$timezone_offset = +8; // us central time (gmt-6) for me
if(isset($reset_req)){
$request_date2 = strtotime($reset_req)+$timezone_offset*60*60;
$current = time();
} else {
echo '$reset_req was not set';
exit;
}
echo "current time= " . $current . "<br />";
echo "time req made=" . $request_date2 . "<br />";
$timediff = $current - $request_date2; // in seconds
if($timediff < (2*3600))//how to calculate 2 hours here
{
echo "less than 7200 sec have past since $request_date2. Past: $timediff seconds";
}else{
echo "more than 7200 sec have past since $request_date2. Past: $timediff seconds";
}
?>

$hour = 3600; //an hour has 3600 seconds
if($timediff < 2 * $hour )
{
//do something
}

$timediff is in seconds. So you have to convert that to hours or convert the 2 hours to seconds and then need to compare like as follows:
replace
if($timediff < 2 hours)//how to calculate 2 hours here
{
//do something
}
with
if($timediff < (2*3600))//how to calculate 2 hours here
{
//do something
}

Try this
<?php
$reset_req = "2015-06-30 11:30:23";
//set default timezone here
date_default_timezone_set("Asia/Kuala_Lumpur");
$request_date2 = '';
if(isset($reset_req))
{
$request_date2 = strtotime($reset_req);
}
echo "Current time = ".time();
echo"<br/>";
echo "Time req made =".$request_date2;
echo"<br/>";
$timediff = time() - $request_date2; // in seconds
echo "<br>Time Differnce : ".$timediff;
//how to calculate 2 hours here
if($timediff < 2*3600)
{
//do something
}
?>

Related

how to check if time is more than 30minute?

I have saved a time. I would like to check whether the saved time is 30 minutes greater than the current time. You can see in the code what I have done so far but it doesn't work.
I would need some help fixing that code.
$current = "08:05";
$to_check = date('h:i');
if($to_check > $current + strtotime('30 minute')){
echo "greater";
}
else {
echo "not greater";
}
First, your $current isn't the current time, $to_check is, so your variable names are misleading.
That being said, store your "08:05" as a Unix timestamp then see if the difference between the two is greater than 30 * 60.
$seconds = 1800; // 30 mins
$time1 = strtotime($db_time) + $seconds;
if(time() >= $time1)
echo "Time's up!"
else
echo "time has not expired";
This should work for you:
<?php
$current = date('H:i');
$to_check = date('H:i', strtotime('+30 minutes'));
$to_check = date('H:i', strtotime($record['date'])); //If value is from DB
if($to_check > $current){
echo "greater";
}
else {
echo "not greater";
}
Save time using time function this would give you time in seconds from 1970 so for example current time is 1501137539 and after 30 minutes it would be (1501137539 + 30*60) so you would just need to check if difference b/w current time and stored time is greater that 30*60 then half an hour is over.
Try this snippet:
function x_seconds($to_check = 'YYYY-mm-dd H:i:s') {
$to_check = strtotime($to_check);
$current = time() + 1800; //We add 1800 seconds because it equals to 30 minutes
return ($current>=$to_check) ? true : false;
}
Or go pro, and have a custom "seconds since", just because you can?
function x_seconds($to_check = 'YYYY-mm-dd H:i:s', $seconds = 1800) {
$to_check = strtotime($to_check);
$current = time() + $seconds; //We add x seconds
return ($current>=$to_check) ? true : false;
}
Example usage:
$date = date('Y-m-d H:i:s', '2017-07-27 05:00');
if(x_seconds($date)):
print "Is within 30 minutes.";
else:
print "IS NOT within 30 minutes";
endif;
Try this to solve the issue
$current = strtotime('12:00:00');
$to_check = strtotime(date('H:i:s'));
$newtime = round(( $to_check - $current ) /60 );
if($newtime > 30){
echo "greater";
}else {
echo "not greater";
}

Count overall time between two timestamps per user

Currently I'm stuck with some MySQL queries.
I have a table like this:
ID|USERID|USERNAME|STARTTIME|ENDTIME|COMMITTYPE
The users click buttons in a frontend -> Start <- and -> Stop <-.
This creates a db entry with their respective duties, starttime and endtime. So, each click on start creates a new row/entry in the db and will get finished by the click on the stop button.
My problem, is there a chance to count the overall time between the start time and the end time per user and commit type?
This probably work
SELECT USERID, COMMITTYPE, MIN(STARTTIME), MAX(ENDTIME),
SUM(TIME_TO_SEC(TIME_DIFF(ENDTIME - STARTTIME))/3600) hours FROM tablename
GROUP BY USERID, COMMITTYPE
Do you refer to something like this?
SELECT COMMITTYPE, USER, (ENDTIME - STARTTIME) AS ELLAPSED_TIME
FROM YOUR_TABLE GROUP BY COMMITTYPE, USERID;
SELECT DATEDIFF('new_date', 'old_date');
// eg
SELECT DATEDIFF('2006-04-01','2006-04-01');
IG GETTING USE LINUX
<?php
// Set timezone
date_default_timezone_set("UTC");
// Time format is UNIX timestamp or
// PHP strtotime compatible strings
function dateDiff($time1, $time2, $precision = 6) {
// If not numeric then convert texts to unix timestamps
if (!is_int($time1)) {
$time1 = strtotime($time1);
}
if (!is_int($time2)) {
$time2 = strtotime($time2);
}
// If time1 is bigger than time2
// Then swap time1 and time2
if ($time1 > $time2) {
$ttime = $time1;
$time1 = $time2;
$time2 = $ttime;
}
// Set up intervals and diffs arrays
$intervals = array('year','month','day','hour','minute','second');
$diffs = array();
// Loop thru all intervals
foreach ($intervals as $interval) {
// Create temp time from time1 and interval
$ttime = strtotime('+1 ' . $interval, $time1);
// Set initial values
$add = 1;
$looped = 0;
// Loop until temp time is smaller than time2
while ($time2 >= $ttime) {
// Create new temp time from time1 and interval
$add++;
$ttime = strtotime("+" . $add . " " . $interval, $time1);
$looped++;
}
$time1 = strtotime("+" . $looped . " " . $interval, $time1);
$diffs[$interval] = $looped;
}
$count = 0;
$times = array();
// Loop thru all diffs
foreach ($diffs as $interval => $value) {
// Break if we have needed precission
if ($count >= $precision) {
break;
}
// Add value and interval
// if value is bigger than 0
if ($value > 0) {
// Add s if value is not 1
if ($value != 1) {
$interval .= "s";
}
// Add value and interval to times array
$times[] = $value . " " . $interval;
$count++;
}
}
// Return string with times
return implode(", ", $times);
}
?>
///
echo dateDiff("2010-01-26", "2004-01-26") . "\n";
echo dateDiff("2006-04-12 12:30:00", "1987-04-12 12:30:01") . "\n";
echo dateDiff("now", "now +2 months") . "\n";
echo dateDiff("now", "now -6 year -2 months -10 days") . "\n";
echo dateDiff("2009-01-26", "2004-01-26 15:38:11") . "\n";
OUTPUT
6 years
18 years, 11 months, 30 days, 23 hours, 59 minutes, 59 seconds 2
months 6 years, 2 months, 10 days 4 years, 11 months, 30 days, 8
hours, 21 minutes, 49 seconds

Mysql database timestamp query using php

Mysql database timestamp query using php
I inserted into database a timestamp value set to 3 hours a head as follows
//For 3 hours ahead of time
$reciever_time = date("Y-m-d H:i:s", strtotime('+3 hours'));
now once its upto 3 hours, i need to echo "3 hours is due" but the code below keeps echoing "its not yet 3 hours" even though
3 hours is due. any help
<?php
$link = mysqli_connect("localhost", "sectona", "secBBN", "sectonadb");
$q = "SELECT id,reciever_time FROM indextime WHERE id='10'";
$qu = mysqli_query($link, $q);
while($row=mysqli_fetch_array($qu, MYSQL_ASSOC)){
$id = $row['id'];
$timest = $row['reciever_time'];
}
//60secx10min is 600milisec
//60secx30min is 1800
// 30 min = 1800
// 1 hour = 1800 x2
//12 hour = 3600 x12
//1 day = 3600 x24
$time = strtotime($timest);
$curtime = time();
// execute data that is due in 3 hours
if(($curtime-$time) >= 10800) {
print "3 hours is due then update";
}
else{
print "its not yet 3 hours";
}
?>
Try this:
if(($time - $curtime) >= -10800) {
print "3 hours is due then update";
} else {
print "its not yet 3 hours";
}
Only convert the 10800 to negative.
You can try:
$link = mysqli_connect("host","user","password","DBname");
$q = "SELECT id,reciever_time FROM indextime WHERE id='10' LIMIT 1";
$qu = $link->query($q);
$row = mysqli_fetch_object($qu);
$id = $row->id;
$timest = $row->reciever_time;
$time = strtotime($timest);
$curtime = time();
$message = ($curtime - $time) >= 10800 ? "3 hours is due then update" : "its not yet 3 hours";
print $message;
in PHP you want to use the the date_diff function to get the difference in time
try:
if(date_diff($time,$curtime) >= 10800){

How to convert 'X hours Y minutes' time string into z minutes in php

I have been stuck with php date time conversion. I have to convert a dynamic time string like 'd days X hours Y minutes' into the total minutes. This time string is dynamic and returned by some third party API. This could be like 'X hours Y minutes', 'Y minutes' etc..
Please help me if someone is having any clue for this.
Thanks in advance.
As Joe replied, here a little push on your way. Note the + in front, as we are adding. We could turn them both into date objects and do a diff() to get the mentioned DateInterval of course.
$apiTimeStamp = strtotime("+1 weeks 2 days 4 hours 2 seconds");
echo abs($apiTimeStamp - time()) / 60;
you can try this:
<?php
$min=0;
$arr = '1 hours 20 minutes';
$a=explode(' ',$arr);
if($a[1] == 'hours')
{
$min = $min+ $a[0]*60;
}
if($a[3] == 'minutes')
{
$min =$min+ $a[2];
}
if($a[1] == 'minutes')
{
$min = $min+ $a[0];
}
echo "'".$min." minutes"."'";
?>
<?php
$apistring = "10 Hours 15 Minutes";
preg_match("#([\d]+)[/\s]+(?i)(?=hours)#", $apistring, $hours);
preg_match("#([\d]+)[/\s]+(?i)(?=minutes)#", $apistring, $minutes);
if (is_numeric($hours[1])==true) {
$intHourMinutes = $hours[1]*60;
}
else {
$intHourMinutes = 0;
}
if (is_numeric($minutes[1])==true) {
$intMinutes = $minutes[1];
}
else {
$intMinutes = 0;
}
$totalminutes=$intHourMinutes+$intMinutes;
print_r($totalminutes);
?>

Calculate the difference between date/times in PHP

I have a Date object ( from Pear) and want to subtract another Date object to get the time difference in seconds.
I have tried a few things but the first just gave me the difference in days, and the second would allow me to convert one fixed time to unix timestamp but not the Date object.
$now = new Date();
$tzone = new Date_TimeZone($timezone);
$now->convertTZ($tzone);
$start = strtotime($now);
$eob = strtotime("2009/07/02 17:00"); // Always today at 17:00
$timediff = $eob - $start;
** Note ** It will always be less than 24 hours difference.
Still gave somewhat wrong values but considering I have an old version of PEAR Date around, maybe it works for you or gives you an hint on how to fix :)
<pre>
<?php
require "Date.php";
$now = new Date();
$target = new Date("2009-07-02 15:00:00");
//Bring target to current timezone to compare. (From Hawaii to GMT)
$target->setTZByID("US/Hawaii");
$target->convertTZByID("America/Sao_Paulo");
$diff = new Date_Span($target,$now);
echo "Now (localtime): {$now->format("%Y-%m-%d %H:%M:%S")} \n\n";
echo "Target (localtime): {$target->format("%Y-%m-%d %H:%M:%S")} \n\n";
echo $diff->format("Diff: %g seconds => %C");
?>
</pre>
Are you sure that the conversion of Pear Date object -> string -> timestamp will work reliably? That is what is being done here:
$start = strtotime($now);
As an alternative you could get the timestamp like this according to the documentation
$start = $now->getTime();
To do it without pear, to find the seconds 'till 17:00 you can do:
$current_time = mktime ();
$target_time = strtotime (date ('Y-m-d'. ' 17:00:00'));
$timediff = $target_time - $current_time;
Not tested it, but it should do what you need.
I don't think you should be passing the entire Date object to strtotime. Use one of these instead;
$start = strtotime($now->getDate());
or
$start = $now->getTime();
Maybe some folks wanna have the time difference the facebook way. It tells you "one minute ago", or "2 days ago", etc... Here is my code:
function getTimeDifferenceToNowString($timeToCompare) {
// get current time
$currentTime = new Date();
$currentTimeInSeconds = strtotime($currentTime);
$timeToCompareInSeconds = strtotime($timeToCompare);
// get delta between $time and $currentTime
$delta = $currentTimeInSeconds - $timeToCompareInSeconds;
// if delta is more than 7 days print the date
if ($delta > 60 * 60 * 24 *7 ) {
return $timeToCompare;
}
// if delta is more than 24 hours print in days
else if ($delta > 60 * 60 *24) {
$days = $delta / (60*60 *24);
return $days . " days ago";
}
// if delta is more than 60 minutes, print in hours
else if ($delta > 60 * 60){
$hours = $delta / (60*60);
return $hours . " hours ago";
}
// if delta is more than 60 seconds print in minutes
else if ($delta > 60) {
$minutes = $delta / 60;
return $minutes . " minutes ago";
}
// actually for now: if it is less or equal to 60 seconds, just say it is a minute
return "one minute ago";
}

Categories