I want to set a link expiration date with php:
I want that when user creates a new short link on my website it should be automatically deleted on the fifth day of creation.
I am totally confused with the following code. I want to put this code on user's notification page, so that it can inform them how many minutes are remaing for the link to be expired.
<?php
$created=time();
$expire=$created + 5;
$total_minutes=$expire / 5 / 60;
echo "Link expires in $total_minutes minutes";?>
It outputs an unexpected long number.
How can I implement this code so that it can output 7200 or remaining minutes?
time() returns UNIX timestamp.
If you want human readable output, look into DateTime class in PHP: http://php.net/manual/en/class.datetime.php
Example:
<?php
$created = new DateTime('now');
$expiration_time = new DateTime('now +5minutes');
$compare = $created->diff($expiration_time);
$expires = $compare->format('%i');
echo "Your link will expire in: " . $expires . " minutes";
?>
The php function time() returns in seconds (since the Unix Epoch).
You adding "5" is just five seconds.
For five days you need to add sum of 5 * 24 * 60 *60 which is the number of seconds for five days.
In code:
$created = time();
$expires = $created + (5 * 24 * 60 * 60);
if ($expires < time()) {
echo 'File expired';
} else {
echo 'File expires in: ' . round(((time() + 1) - $created) / 60) . ' minutes';
}
Please refer to PHP: time()
<?php
$created = strtotime('June 21st 20:00 2015'); // time when link is created
$expire = $created + 432000; // 432000 = 5 days in seconds
$seconds_until_expiration = $expire - time();
$minutes_until_expiration = round($seconds_until_expiration / 60); // convert to minutes
echo "Link expires in $minutes_until_expiration minutes";
?>
Note that $created shouldn't be made at script runtime, but saved somewhere, otherwise this script will always report that the link expires in 5 days.
Related
PHP Function to convert time() seconds to time format Hour:Minutes
function secondsToTime($seconds) {
$dtF = new \DateTime('#0');
$dtT = new \DateTime("#$seconds");
// return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
return $dtF->diff($dtT)->format('%h:%i');
}
echo secondsToTime(time());
I need a function for something like:
If time now is 23:41 (hour:minute) to show 23:40
If time now is 23:46 (hour:minute) to show 23:45
If time now is 23:47 (hour:minute) to show 23:45
If time now is 23:49 (hour:minute) to show 23:45
If time now is 23:52 (hour:minute) to show 23:50
But the output to be show by time() format seconds so this way i can check via mysql how many rows updated from time() format show 23:45 if time now is 23:49 so in past 4 minutes ...
You need to round the minutes and then reformat your output date.
There's some gotchas hidden in here. As you can end up with 60 minutes (should be 00) and 24 hours (also should be 00). So special checks are put in place to catch that.
Also, you way of getting the current time is very convoluted. Getting "now" gets the same value which is what DateTime() gets by default.
function secondsToTime() {
$now = new \DateTime();
$cminutes = $now->format('i');
$hour = $now->format('H');
$nminutes = (round($cminutes)% 5 === 0) ? round($cminutes) : round(($cminutes + 5 / 2) / 5 ) * 5;
if ($nminutes > $cminutes) {
$nminutes -= 5;
}
if ($nminutes === 60) {
$nminutes = 0;
$hour++;
}
if ($hour === 24) {
$hour = 0;
}
return sprintf('%02d:%02d', $hour, $nminutes);
}
echo secondsToTime();
Demo
I need add extra 24 hours to my default time and store in database like start time is = default time, end time is = start time + 24 hours.
I already try this way. hear is the code.
<?php
date_default_timezone_set("Asia/Colombo");
$time = date("H:i:s");
$validtime = '24:00:00';
$endtime = strtotime($time + $validtime);
echo date('H:i:s', $endtime);
$bookname= $_GET['id'];
$link=mysqli_query($conn, "update reserve_table set username='$_SESSION[username]', bookname='$bookname', reservetime='$time', endtime='$endtime'");
?>
and pop up this error
Notice: A non well formed numeric value encountered in
/opt/lampp/htdocs/Lowa/student/reserve.php on line 33
Notice: A non well formed numeric value encountered in
/opt/lampp/htdocs/Lowa/student/reserve.php on line 33 05:30:00
PHP cannot add dates in the '24:00:00' format. This is a strings, not a number or "time" thingy. You can add time when it is expressed as a number in seconds. So this will work:
// get time in seconds as an integer
$time = time();
// show it in seconds and formated
echo "In seconds: $time formated: " . date("Y-m-d H:i:s", $time);
// add a day
echo "<br>Add a day.<br>";
$time += 24 * 60 * 60;
// show it in seconds and formated
echo "In seconds: $time formated: " . date("Y-m-d H:i:s", $time);
time() return the current time in seconds. We then add a whole day worth of seconds and convert it to the format you need.
In my code I pretty much send a token to the database with the
date('Y-m-d H:i:s');
function. But I am checking to see if the timestamp I sent if greater than 60 seconds if so i echo yes and else no. I keep getting no and I know its more than a minute because i time it. I've seen post about this but they're using specific dates and I am just going on when a user submits a form and checking if the token is 60 seconds old. Here is my code
php
<?php
require_once('db_login.php');
$stmtToken = $handler->prepare("SELECT * FROM email_token");
$stmtToken->execute();
$rowToken = $stmtToken->fetch();
$date = $rowToken['time_stamp'];
if($date > time() + 60) {
echo 'yes';
} else {
echo 'no';
}
?>
You can also play with dates in different manners. All four lines here are equivalent:
$now = (new \DateTime(date('Y-m-d H:i:s')))->getTimestamp();
$now = (new \DateTime('now'))->getTimestamp();
$now = (new \DateTime())->getTimestamp();
$now = time();
And then you can compare in this manner:
$tokenExpirationTimestamp = (new \DateTime($date))
->modify('+60 seconds')
->getTimestamp();
$isTokenExpired = $tokenExpirationTimestamp < time();
if ($isTokenExpired) {
// ...
}
When you compare times and dates you can either use datetime or strtotime.
Using strings will not work as expected in all cases.
In comments you mentioned how you want to compare, and you need to add the 60 seconds to the "date", not the time().
if(strtotime($date) + 60 < time()) {
I have activity start time and and total hour i just want to find the end time of that activity i mean time when activity finished ?
for example I start my activity
for
$hour = 24:60:08 // 24 hour 60 min 8 min total hour
$starttime = 13:09 // using 24 hour format it 01:09
//means activity start at = 13:09
$endtime = ?
I want to find out the the time finished time of an activity
Thanks
You can with adding to time exploded hour like following:
$hour = '24:60:08';
$starttime = '13:09';
$times = explode(':', $hour);
$timestamp = strtotime($starttime) + ($times[0] * 3600 + $times[1] * 60 + $times[2]);
$endtime = date('H:i', $timestamp);
echo $endtime; // 14:09
Explain:
24 = 24(hours) * 60(mins) * 60(secs)
60 = 60(mins) * 60(secs)
08 = 8(sec)
It appears like you have a start time of an activity and then a duration of how long it ran and you want to compute what's the end time. Your question becomes unclear by your use of non descriptive variable names nor any comments. You can do
<?php
$duration = "25:00:08";
$starttime = "13:09";
list($hours,$minutes,$seconds) = explode(":",$duration);
$totalTime = $seconds+($minutes*60)+($hours*3600);
$endTime = date("h:i",strtotime($starttime)+$totalTime);
echo $endTime;
?>
Sidenote: 24:60:08, 60 minutes is nothing. That's 25 hours 0 minutes and 8 seconds
If you want to get the time elapsed to process something, let's say to execute a function, you can easily do it with PHP microtime.
Assume you want to find time elapsed to execute function test, here how you do this.
public function test()
{
$time_start = microtime(true);
/*
Your code
goes here
*/
$time_end = microtime(true);
$execution_time = (($time_end - $time_start) / 60) * 60;
echo $execution_time; //This will show you the execution time in seconds.
}
If you want, you can add this seconds to any previous time stamp you saved, in order to get the execution terminated time in hh:mm:ss format. Hope this helps.
Cheers!
I am unable to understand exactly what you are looking for
<?php
$hour = "24:60:08"; // 24 hour 60 min 8 min total hour
$starttime = "13:09";
$hourArray=explode(":", $hour);
$starttimeArray=explode(":", $starttime);
$endtimearray=array();
for ($i=0;$i<3;$i++){
//Verifyng time is set else making it zero
if (!isset($hourArray[$i]))
$hourArray[$i]=0;
if (!isset($starttimeArray[$i]))
$starttimeArray[$i]=0;
$endtimearray[$i]=$hourArray[$i]-$starttimeArray[$i];
}
echo $endtimearray[0];
for ($i=1;$i<3;$i++)
echo ":$endtimearray[$i]";
Hopefully This is what you are looking for.
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";
}