Time() By 5 Minutes Select - php

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

Related

Difference between durations

I am creating a timesheet whereby it shows expected and actual hours.
The durations are saved like the below
23:15 - 23 hours and 15 mins
25:45 - 25 hours and 45 mins
I need to work out the difference in hours and mins between the two (extra hours worked)
I have tried the below
$acutal=='23:15';
$expected=='25:45';
$start_time = new DateTime("1970-01-01 $acutal:00");
$time = $start_date->diff(new DateTime("1970-01-01 $expected:00"));
This does work, however when the hours are over 24:00 it throws an error (obviously because it's reading it as time)
Uncaught exception 'Exception' with message 'DateTime::__construct():
Failed to parse time string (1970-01-01 25:45:00)
Is there another way to do this?
You could check if the number of hours are greater than 24, and if so, add a day, and remove 24 hours.
$actual='23:15';
$expected='25:45';
$day = 1;
list($hrs, $min) = explode(':', $expected);
if ($hrs > 24) { $day += 1; $hrs -= 24; }
$start_time = new DateTime("1970-01-01 $actual:00");
$time = $start_time->diff(new DateTime("1970-01-$day $hrs:$min:00"));
echo $time->format('%hh %Im');
Output:
2h 30m
Please also note that == is used to compare, not to assign.
You can also change the if ($hrs > 24) by while(), if there is 48 hours or more.
edit
As pointed out by #CollinD, if the time exceed the number of days of the month, it will fail. Here is another solution:
$actual='23:15';
$expected='25:45';
list($hrs, $min) = explode(':', $actual);
$total1 = $min + $hrs * 60;
list($hrs, $min) = explode(':', $expected);
$diff = $min + $hrs * 60 - $total1;
$start_time = new DateTime();
$expected_time = new DateTime();
$expected_time->modify("+ $diff minutes");
$time = $start_time->diff($expected_time);
echo $time->format('%hh %Im');
You can do it manually by keeping track of the number of minutes worked - this will be exact and will also allow you to show negative differences.
<?php
// get the difference in H:mm between two H:mm
function diff_time($actual, $expected) {
$diff_mins = mins($actual) - mins($expected);
return format_mins($diff_mins);
}
// convert a HH:mm to number of minutes
function mins($t) {
$parts = explode(':', $t);
return $parts[0] * 60 + $parts[1];
}
// convert number of minutes into HH:mm
function format_mins($m) {
$mins = $m % 60;
$hours = ($m - $mins) / 60;
// format HH:mm
return $hours . ':' . sprintf('%02d', abs($mins));
}
var_dump(diff_time('23:15', '25:45'));
var_dump(diff_time('25:15', '23:45'));
This outputs:
string(5) "-2:30"
string(4) "1:30"
.. first, 2:30 less than expected, for the second 1:30 more than expected.
You can try using datetime functions but it seems a lot more straightforward to me to treat the times as string, use split or explode to get hours and minutes, convert to integers, get the difference in minutes and convert it back to hours and minutes (integer divide by 60 and remainder).
$t1=explode(':',$expected);
$t2=explode(':',$actual);
$d=60*($t1[0]-$t2[0])+t1[1]-t2[1];
$result=str_pad(floor($d/60),2,'0',STR_PAD_LEFT).':'.str_pad($d%60,2,'0',STR_PAD_LEFT);

PHP count up timer from variable

I have a page that shows the status of a TeamSpeak server on which I user ServerQuery to get the server's uptime using $uptime. This displays the server uptime as a total in seconds and I convert it to days, hours, minutes and seconds using
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');
I output the uptime in the above format using secondsToTime($uptime); but I would like for the output to count up from the original output once the page is loaded instead of having to refresh the page to get the new uptime.
Thanks in advance.
You should use JavaScript to make a simple timer.
var timeelm, time, days, hours, minutes, seconds;
timeelm = document.getElementById("time");
time = timeelm.innerHTML;
days = parseInt(time.split(" ")[0]);
hours = parseInt(time.split(" ")[2]);
minutes = parseInt(time.split(" ")[4]);
seconds = parseInt(time.split(" ")[7]);
timerGo();
function timerGo() {
seconds++;
if (seconds == 60) {
minutes++;
seconds = 0;
}
if (minutes == 60) {
hours++;
minutes = 0;
}
if (hours == 24) {
days++;
hours = 0;
}
timeelm.innerHTML = days+" days, "+hours+" hours, "+minutes+" minutes and "+seconds+" seconds";
setTimeout(timerGo, 1000);
}
Note: Make sure that your webpage has an element assigned an ID of time.
Check out this fiddle.

php strtotime in seconds and minutes

i use ths method to find the difference between two timestamp and get the number of seconds between those two times, and i refresh the information with jquery like a counter.
$diff = strtotime(date('Y-m-d H:i:s')) - strtotime('2014-06-25 14:50:03');
$time = intval(date('s', $diff));
echo $time;
When the difference is more than 60 seconds, the $time comes back to 0, like a reset.
i would like to display 1 min XX s for example
The s flag for date() will never return a value greater than 59 as it only represents the current number of seconds of a given time which can never be more than 59 before rolling over into a new minute.
If you want the total number of seconds you can actually remove your second line of code as the difference between two Unix Timestamps is always in seconds:
$time = strtotime(date('Y-m-d H:i:s')) - strtotime('2014-06-25 14:50:03');
echo $time;
If you want to display this as minutes and seconds you can use DateTime() which offers better tools for this:
$now = new DateTime();
$then = new DateTime('2014-06-25 14:50:03');
$diff = $now->diff($then);
echo $diff->format('%i minutes %s seconds');
format the date
$diff = strtotime(date('Y-m-d H:i:s')) - strtotime('2014-06-25 14:50:03');
$time = date('i:s', $diff);
echo $time;
Pass time like 1 & now 2
function diffrencePassTimeAction($DataTime){
$im = $DataTime - strtotime("now");
return $im;
}
Future time like 2 & now 1
function diffrenceFuturTimeAction($DataTime){
$im = strtotime("now") - $DataTime;
return $im;
}
this function delete (-less)
function diffrencePassTimeAction($DataTime){
if ($DataTime > 0)
return $DataTime - strtotime("now");
else
return strtotime("now"); // OR return 0;
}

How to calculate the time difference between unix time stamps?

I am creating time stamps in PHP using time();
I have the $current_time and $purchase_time. How do I make sure that purchase_time is less than 24 hours of current time?
If they are UNIX timestamps, then you can calculate this by yourself really easy, as they are seconds.
$seconds = $current_time - $purchase_time
$hours = floor($seconds/3600);
if ($hours < 24){
//success
}
Since UNIX timestamps are just numbers of seconds, just use the difference:
$purchasedToday = $current_time - $purchase_time < 24 * 60 * 60;
if ($purchasedToday) {
echo 'You just bought the item';
} else {
echo 'You bought the item some time ago';
}
You can construct a DateTime object and then use it's diff() method to calculate the difference between $current_time and $purchase_time:
$currentTime = new DateTime();
$purchaseTime = new DateTime('2011-10-14 12:34:56');
// Calculate difference:
$difference = $currentTime->diff($purchaseTime);
if ($difference->days >= 1) {
echo 'More than 24 hours ago.';
}
This is more reliable than calculating the difference yourself, as this method takes care of timezones and daylight saving time.
Something like this:
$difference=time() - $last_login;
I had use something like this:
<?php
if(date("U", strtotime("-24 hours", $current_time) > date("U", $purchase_time)) {
echo "More then 24 hours you purchased this radio";
}
?>
This works even if the time stamp not is a UNIX-timestamp.

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