PHP Touch() using time() parameter for the past -any limitation? - php

When changing a file's datetimestamp from the current system time to the distant past is there a limit with the time() parameter? With touch(), all the documentation I can see uses the time() parameter which has a future limitation of 100000 seconds:
<?php
$file_pointer = "gfg.txt";
// setting touch time to 5 hours in the past
$time = time() - 18000;
// using touch() function to change the modification
// time of a file to current system time
if (touch($file_pointer, $time))
{
echo ("$file_pointer modification time has been changed to 5 hours in the past.");
}
else
{
echo ("$file_pointer modification time cannot be changed.");
}
?>
What would be the best approach to change it to 1 year in the past or even 5 years in the past? Would the following be the most accepted approach and would it work?:
$time = time() - 31536000;// 1 year
$time = time() - 157680000;// 5 years

use this docs
$time = strtotime("5 years ago");
// or
$time = strtotime("-5 years")

Related

php convert seconds to minutes:seconds only [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 7 years ago.
I am using this function to convert seconds to minutes:
function convert($iSeconds)
{
return date('i:s', mktime(0, 0, $iSeconds));
}
It works great. But if I use this code:
echo convert(3605);
It returns 00:05. But I need to return like this: 60:05
HOW CAN I FORMAT MINUTES:SECONDS???
You can't use mktime() or strtotime() for this kind of conevrsions. You can calculate this manually. You can try this -
function convert($iSeconds)
{
$min = intval($iSeconds / 60);
return $min . ':' . str_pad(($iSeconds % 60), 2, '0', STR_PAD_LEFT);
}
echo convert(7205);
Output
120:05
Fiddle
You can't use the date conversion function since it will not accept minutes > 60 and hours > 24.
The easiest way to do it is to use this function:
function convert($iSeconds)
{
$numMinutes = $iSeconds/60;
$numSeconds = $iSeconds - ($numMinutes * 60);
$numMinutes = $numMinutes."";
$numSeconds = $numSeconds."";
if (strlen($numMinutes) == 1)
$numMinutes = "0".$numMinutes;
if (strlen($numSeconds) == 1)
$numSeconds = "0".$numSeconds;
return $numMinutes.":".$numSeconds;
}
According to the documentation of mktime, for minute:
The number of the minute relative to the start of the hour. Negative values reference the minute in the previous hour. Values
greater than 59 reference the appropriate minute in the following
hour(s).
And for second:
The number of seconds relative to the start of the minute. Negative values reference the second in the previous minute. Values
greater than 59 reference the appropriate second in the following
minute(s).
When you call mktime you are passing a value of 0 for both hours and minutes; with 3605 seconds you are basically "spinning" the seconds hand on the clock 3600/60 times, and then you add those 5 seconds.
So you will have to first manually calculate the correct values for minutes and possibly hours that your given amount of seconds amounts to.
For that, you will need to use mod and intval of the division.
In a very educational format you'd have something like:
function convert($iSeconds) {
$seconds = $iSeconds % 60;
$minutes = intval($iSeconds/60);
$hours = intval($minutes/60);
$minutes = $minutes % 60;
return date('H:i:s', mktime($hours, $minutes, $seconds));
}
https://eval.in/508531
Indeed, this doesn't directly solve the OP, as the number of minutes can be of arbitrary size. As noted, mktime cannot be used to achieve that, as it will always format a "proper" time value, where minutes and seconds are a number between 0-59.

calculating time remaining using php time()

I have a php script where I need to make sure a pre-set "future" time has not passed.
When the time is originally logged (or passed and needs relogged), I am taking:
$newTime = time() + 15000; // 2.5 minutes from "now"
The system is tossing this in the DB no problem and the numbers appear to be correct.
Now, when the page is loaded, it pulls the number from the DB and loads it into the .php file:
error_reporting(E_ALL);
ini_set('display_errors',1);
$tname = $_SESSION['username']."Data";
$results = $conn->query("SELECT val FROM $tname where pri='pettyTimer'") or die(mysqli_error($conn));
//$conn declared elsewhere for connection and does work properly
$row = $results->fetch_assoc();
$timer = $row['val'];
I am then comparing the times:
$now = time();
if ($timer > time()) { //script below
} else {
//more script that seems to be working fine
}
When the original conditional $timer > time() is true I am trying to break down the minutes and seconds of the time remaining and echoing them in a basic format that is readable to the user:
$raw = ($timer - $now);
$minutesLeft = floor($raw / 60000);
$totalMinutes2Mils = $minutesLeft * 60000;
$totalRemainingSecs = round(($raw - $totalMinutes2Mils) / (1000));
echo "You are still laying low from the last job you ran. You still have ".$minutesLeft." Minutes and ".$totalRemainingSecs." Seconds left.";
My problem is, the time does not appear to be shifting when I refresh/reload the page.
I echoed both time() and $timer and they are 15000 milliseconds apart when I first loaded it, so this should only exist (conditional be true) for about 2.5 minutes, but I've been working at least 5 minutes since my last set and it's still at 14 seconds.
Can someone please double check my math to make sure I'm calculating this correctly? Thanks!
The time() function returns the current time in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
http://www.w3schools.com/php/func_date_time.asp
You are treating it as milliseconds, but should be treating it as straight seconds. take about /1000 and you should be ok.
$minutesLeft = floor($raw / 60);
$totalMinutes2Mils = $minutesLeft * 60;
$newTime = time() + (60*2.5); // 2.5 minutes from "now"
time() returns seconds, not milliseconds, so you should add 150 instead of 15000 to get 2:30 minutes.

Strtotime not working as expected

My goal is to compare the current time with the last visited time and if was 5 minutes ago then allow to visit again, else, deny! Here what I have so far
$last_activate = strtotime($last_activ); //$last_activ is TIMESTAMP value retrieved from MySQL database
$current_time = strtotime('now');
if(($current_time - $last_activate) > strtotime('5 minutes')){
//allow access
}
else{
//deny access
}
At the moment, the code above always executes else statement even if $last_activate was 24 hours ago. Anyone knows what point I am missing?
strtotime('5 minutes') means now + 5 minutes. Proof:
echo date("Y-m-d H:i:s", strtotime('5 minutes'));
2013-03-21 19:41:27
Do this instead:
if(($current_time - $last_activate) > 5 * 60){
Replace 5 minutes with 5 minutes ago.

How to return the amount of years passed?

My friend and I are working on a fairly basic uptime script for an IRC Bot.
Here's our code:
function Uptime()
{
global $uptimeStart;
$currentTime = time();
$uptime = $currentTime - $uptimeStart;
$this->sendIRC("PRIVMSG {$this->ircChannel} :Uptime: ".date("z",$uptime)." Day(s) - ".date("H:i:s",$uptime));
}
$uptimeStart is set immediately when the script runs, as time();
for some reason when I execute this function, it starts at 364 days and 19 hours. I can't figure out why.
Your $uptime is not a timestamp as should be used in date(), but a difference in time. You have an amount of seconds there, not a timestamp (that corresponds with an actual date.
just use something like this to cacluate (quick one, put some extra brain in for things like 1 day, 2 hours etc) ;)
$minutes = $uptime / 60;
$hours = $minuts/60 ;
$days = $hours / 24
etc
If you have 5.3 or above, use the DateTime and DateInterval classes:
$uptimeStart = new DateTime(); //at the beginning of your script
function Uptime() {
global $uptimeStart;
$end = new DateTime();
$diff = $uptimeStart->diff($end);
return $diff->format("%a days %H:%i:%s");
}
You won't get anything meaninful by calling date() on that time difference. You should take that time difference and progressively divide with years, months, days, hours, all measured in seconds. That way you'll get what the time difference in those terms.
$daySeconds = 86400 ;
$monthSeconds = 86400 * 30 ;
$yearSeconds = 86400 * 365 ;
$years = $uptime / $yearSeconds ;
$yearsRemaining = $uptime % $yearSeconds ;
$months = $yearsRemaining / $monthSeconds ;
$monthsRemaining = $yearsRemaining % $monthSeconds ;
$days = $monthsRemaining / $daySeconds ;
.. etc to get hours and minutes.
date() function with second argument set to 0 will actually return you (zero-date + (your time zone)), where "zero-date" is "00:00:00 1970-01-01". Looks like your timezone is UTC-5, so you get (365 days 24 hours) - (5 hours) = (364 days 19 hours)
Also, date() function is not the best way to show the difference between two dates. See other answers - there are are already posted good ways to calculate difference between years

Unix timestamp to seconds, minutes, hours

I need to somehow take a unix timestamp and output it like below
Can this be done with MySQL? Or php
Mike 7s ago
Jim 44s ago
John 59s ago
Amanda 1m ago
Ryan 1m ago
Sarah 1m ago
Tom 2m ago
Pamela 2m ago
Ruben 3m ago
Pamela 5h ago
As you can guess i only wanna print the minute, not minutes and seconds(1m 3s ago)
What should I look into?
Yes it can be done. See related post
$before // this is a UNIX timestamp from some time in the past, maybe loaded from mysql
$now = time()
$diff = $now - $before;
if( 1 > $diff ){
exit('Target Event Already Passed (or is passing this very instant)');
} else {
$w = $diff / 86400 / 7;
$d = $diff / 86400 % 7;
$h = $diff / 3600 % 24;
$m = $diff / 60 % 60;
$s = $diff % 60;
return "{$w} weeks, {$d} days, {$h} hours, {$m} minutes and {$s} secs away!"
}
PHP 5.3 and newer have DateTime objects that you can construct with data coming back from a database. These DateTime objects have a diff method to get the difference between two dates as a DateInterval object, which you can then format.
Edit: corrected sub to diff.
Edit 2:
Two catches with doing it this way:
DateTime's constructor doesn't appear to take a UNIX timestamp... unless prefixed with an #, like this: $startDate = new DateTime('#' . $timestamp);
You won't know what the largest unit is without manually checking them. To get an individual field, you still need to use format, but with just a single code... Something like $years = $dateDiff->format('y');
function sECONDS_TO_DHMS($seconds)
{
$days = floor($seconds/86400);
$hrs = floor($seconds / 3600);
$mins = intval(($seconds / 60) % 60);
$sec = intval($seconds % 60);
if($days>0){
//echo $days;exit;
$hrs = str_pad($hrs,2,'0',STR_PAD_LEFT);
$hours = $hrs-($days*24);
$return_days = $days." Days ";
$hrs = str_pad($hours,2,'0',STR_PAD_LEFT);
}else{
$return_days="";
$hrs = str_pad($hrs,2,'0',STR_PAD_LEFT);
}
$mins = str_pad($mins,2,'0',STR_PAD_LEFT);
$sec = str_pad($sec,2,'0',STR_PAD_LEFT);
return $return_days.$hrs.":".$mins.":".$sec;
}
echo sECONDS_TO_DHMS(2); // Output 00:00:02
echo sECONDS_TO_DHMS(96000); // Output 1 Days 02:40:00
PHP's date() function
as well as time() and some others that are linked in those docs
This can also be done in Mysql with date and time functions
You can try my Timeago suggestion here.
It can give outputs like this:
You opened this page less than a
minute ago. (This will update every
minute. Wait for it.)
This page was last modified 11 days
ago.
Ryan was born 31 years ago.
I dont have a mysql server at hand, but a combination of the following commands should get you something like what you want.
DATEDIFF
AND
DATEFORMAT

Categories