Calculate the difference between timestamp - php

I have created registration page and when user click submit button, an activation link is sent to his email and accordingly timestamp is stored in the database. If user click that activation link, I have to check whether that link is clicked before or after 24 hours .
my code :-
function confirmEmail($activation_code){
$this->load->database();
$this->load->helper('date');
echo "activation link will be checked and accordingly flag will be set.";
$activation_sent_timestamp=$this->db->query("SELECT activation_timestamp FROM tbl_user_registration WHERE email_verification_code='$activation_code'");
foreach($activation_sent_timestamp->result() as $res){
$activation_time_from_db=$res->activation_timestamp;
}
echo $activation_time_from_db."\n\r";
$now = time();
$human = unix_to_human($now);
echo $human;
$difference = ($human-$activation_time_from_db);
if($difference < 24) {
echo "correct"
}
else echo "Link expired";
}
I am using codeigniter. How can I do this, this code isnot showing any erros but I dont know is this the right way to calculate 24 hours, I am checking but didnt get anything.please check the code.
SOLVED........ :)

unix_to_human() just returns a human readable form of timestamp
The simplest method is, find the difference between both time stamps, convert to hrs and check if it is less than 24hrs

You may want to use date_diff
See here : DATE_DIFF()

You can use diff for calculation difference and also you can change time format
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

Convert both timestamps to php date('Y-m-d') formats then try date_diff

You can use mysql timediff function in the query.
Looking at your situation you can do this as i have answered in this post
Finding free blocks of time in mysql and php?

$time = time();
$seconds = 86400 // seconds of 24 Hours
SELECT * FROM tbl_user_registration WHERE ( $time - UNIX_TIMESTAMP( activation_timestamp ) >= $seconds )

Related

How to make email link expire after X minutes in php?

I am working on email link expire after some X minutes where X denotes some random date_time. so my motive is to expire the the link after some time what ever I set the date_time in side the $expire_date.
So I just created dummy code myself just in order to sure my code works or not.
$currentDateTime = new \DateTime();
$currentDateTime-> setTimezone(new \DateTimeZone('Asia/kolkata'));
$now = $currentDateTime-> format(' h:iA j-M-Y ');
$expire_date = "02:59PM 26-Mar-2019";
if($now > $expire_date)
{
echo " link is expired";
}
else{
echo " link still alive ";
}
I guess I am missing something in the above code, somehow the above code isn't working if anyone would point out the right direction or some better implementation it would be great.
You are comparing the times as strings. This does not work, as your first formatted string has a leading space.
Instead, try either removing the whitespace, or better, compare the times as DateTime objects:
$timezone = new \DateTimeZone('Asia/kolkata');
// Create the current DateTime object
$currentDateTime = new \DateTime();
$currentDateTime-> setTimezone($timezone);
// Create the given DateTime object
$expire_date = "02:59PM 26-Mar-2019";
$expireDateTime = \DateTime::createFromFormat($expire_date, 'h:iA j-M-Y');
// Compare the objects
if($currentDateTime > $expireDateTime)
{
echo " link is expired";
}
else{
echo " link still alive ";
}
If you want to compare dates in PHP, your best bet is to use UNIX time stamps. A UNIX time stamp is the number of seconds since the UNIX epoch (00:00:00 Thursday, 1 January 1970).
time() will return the current UNIX time stamp.
strtotime() will convert a date string into a UNIX time stamp.
So replacing these two lines:
$now = $currentDateTime-> format(' h:iA j-M-Y ');
$expire_date = "02:59PM 26-Mar-2019";
With these:
$now = time();
$expire_date = strtotime("02:59PM 26-Mar-2019");
Should solve your problem.
You are comparing date strings which will not work. You have to parse the string to a datetime object or timestamp before you can compare these values.
For example, using timestamps:
$expire_date = "02:59PM 26-Mar-2019";
if (time() > strtotime($expire_date)) {
echo "link is expired";
} else {
echo "link still alive ";
}
All you have to do is use strtotime function and add inside date function and here you can specify day, hour, minutes, seconds as a perimeter. This way you can set time manually by adding +5 minutes or so on..
date_default_timezone_set("Asia/Kolkata"); // set time_zone according to your location
$created = "2020-08-14 17:52"; // time when link is created
$expire_date = date('Y-m-d H:i',strtotime('+1 minutes',strtotime($created)));
//+1 day = adds 1 day
//+1 hour = adds 1 hour
//+10 minutes = adds 10 minutes
//+10 seconds = adds 10 seconds
//To sub-tract time its the same except a - is used instead of a +
$now = date("Y-m-d H:i:s"); //current time
if ($now>$expire_date) { //if current time is greater then created time
echo " Your link is expired";
}
else //still has a time
{
echo " link is still alive";
}

php code calculate 30 minutes from created datetime field in table

In my table there is a created datetime field in which data inserting like 2016-05-25 11:50:35.
Suppose my insertion time is 11:50 and current time is 12:10,so the differnce is 20 mins.
now i need to check is get this difference in one variable and check if differnce > 30 then the edit link will be invisible else visible.
below is my code..
i get extracted mins from my created datetime field from database.
$var1 = $post['ShipperRating']['created'];
$time1 = date('i', strtotime($var1));
$finaltime = $time1;
echo $finaltime;
$createdDateTime = new DateTime($post['ShipperRating']['created']);
$createdDateTime->modify('+30 minutes');
if ($createdDateTime >= new DateTime()) {
echo 'Edit';
}
Using strtotime (http://php.net/manual/en/function.strtotime.php) will work...
$var1 = $post['ShipperRating']['created'];
$time1 = strtotime($var1);
$finaltime = strtotime('+ 30 minutes',$time1);
echo date('Y-m-d H:i:s',$finaltime);
If you want to do it by PHP then you have to refresh page after 30 minutes to and calculate the time from server which already show in other answers. You can use header function to set time for refreshing page
header("Refresh: 300;url='http://example.com/example'");
Use following Function
(1800000 miliseconds =30mintues)
window.setTimeout('removelink()',1800000); //
function removelink()
{
//write Code to Remove your Link
}

PHP MYSQL compare time with created in database

I want to check if 30 min passed after created time in database. created is a time column having time stamp in this format 1374766406
I have tried to check with date('m-d-y H:i, $created) but than of course it is giving human readable output so don't know how to perform check if current time is not reached to 30min of created time.
Something like if(created > 30){}
Try this:
$created = // get value of column by mysql and save it here.
if ($created >= strtotime("-30 minutes")) {
// its over 30 minutes old
}
The better approach is to use DateTime for (PHP 5 >= 5.3.0)
$datenow = new DateTime();
$datenow->getTimestamp();
$datedb = new DateTime();
$datedb->setTimestamp(1374766406);
$interval = $datenow->diff($datedb);
$minutes = $interval->format('%i');
$minutes will give you the difference in minutes, check here for more
http://in3.php.net/manual/en/datetime.diff.php
Here is the working code
http://phpfiddle.org/main/code/jxv-eyg
You need to use strtotime(); to convert the date in human form back to a timestamp, then you can compare.
EDIT: Maybe I misread.
So something like;
if(($epoch_from_db - time()) >= 1800){
//do something
}

Subtract php format date and set the difference value in a textbox [duplicate]

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.

Comparing DateTime?

I've been doing a good amount of research with this, and used a few codes to get to know how to make this work, but nothing has worked the way I wanted it to, or hasn't worked at all.
The code is:
<?php
$time1 = $user['last_active'];
$time2 = "+5 minutes";
if (strtotime($time1) > strtotime($time2)) {
echo "Online!";
}else{
echo "Offline!";
}
?>
It is supposed to compare the two variables, and find out if the last active variable is greater or less than 5 minutes, and if it is greater, appear offline. I do not know what's wrong as the NOW() updates on each page and stops if the user is not logged in. Any suggestions or help? Thanks.
The $time1 variable is coming from a fetched array that gets the ['last_active'] information that updates on each page.
I fixed my code, but it still doesn't work right, however, I think I have managed to get further than I was..
<?php
$first = new DateTime();
$second = new DateTime($user['last_active']);
$diff = $first->diff( $second );
$diff->format( '%H:%I:%S' );
if($diff->format( '%H:%I:%S' ) > (strtotime("5 minutes"))){
echo "Offline";
}else{
echo "Online";
}
?>
What can I do at this point?
Nobody pointed out that you actually have a bug. The "current time" will never be greater than "the current time +5 minutes"
Your first code sample will work right if you instead use "-5 minutes" as the "online threshold."
Also, comparing a timestamp without date to the output of strtotime() as you do in the second code is not a proper comparison. It has two problems:
Each time a new day comes around, the same time value will be repeated.
The output of strtotime is an integer representing seconds-since-epoch; the output of format() is a textual representation of hours:minutes:seconds within the current date.
As for your question how to calculate time between 2 dates / time, please view the solution on the following posts, that should give you enough information! (duplicate ? )
Calculate elapsed time in php
And here
How to get time difference in minutes in PHP
EDIT AS YOU PLEASE
<?
$first = new DateTime(); // this would hold your [last active]
//$first->modify("-6 minutes");
$second = new DateTime("NOW");
$difference = $second->diff( $first ); // second diff first
if ($difference->format('%i') > 5) { // comparing minutes only in example ( %i )
echo "The user is AFK";
} else {
echo "user might still be active";
}
?>

Categories