How to get the total number of monts, days, and minutes from a given minute. Say for example given a value in minutes 93366 should return 2 months ,5 days and 5 hours. This is what I've tried so far.
function convert_minutes($minutes, $output) {
if ($minutes >= 43833) {
$whole_month = 0;
$decimal_month = 0;
$label = "";
$months = $minutes / 43833;
list($whole_month, $decimal_month) = sscanf($months, '%d.%d');
if ($months > 1) {
$label = "months";
} else {
$label = "month";
}
$output .= $months . " " . $label;
$decimal_month = "0." . $decimal_month;
if ($decimal_month != 0) {
return $this->convert_minutes($decimal_month, $output);
} else {
return $output;
}
} elseif ($minutes >= 1440) {
$whole_day = 0;
$decimal_day = 0;
$label = "";
$days = $minutes / 1440;
list($whole_day, $decimal_day) = sscanf($days, '%d.%d');
if ($days > 1) {
$label = "days";
} else {
$label = "day";
}
$output .= $days . " " . $label;
$decimal_day = "0." . $decimal_day;
if ($decimal_day != 0) {
return $this->convert_minutes($decimal_day, $output);
} else {
return $output;
}
} elseif ($minutes >= 60) {
$whole_minutes = 0;
$decimal_minutes = 0;
$label = "";
$min = $minutes / 60;
list($whole_minutes, $decimal_minutes) = sscanf($min, '%d.%d');
if ($min > 1) {
$label = "minutes";
} else {
$label = "minute";
}
$output .= $min . " " . $label;
$decimal_minutes = "0." . $decimal_minutes;
if ($decimal_minutes != 0) {
return $output . " and " . $decimal_minutes . " minutes";
} else {
return $output;
}
}
}
EDIT
I just wanted to get the estimate. Assuming 1 hour is 60 minutes and 1 day is 1440 minutes and 1 month is 43,200. I am developing a document tracking system and would just like to calculate how long a document stayed in a particular office based on the date received and date released.
You can use floor and mod operator.
Floor rounds down a number.
The modulo operator will give you what is left if split evenly.
Example 5%2 = 1
Since 2*2 = 4 and the remaining is 1.
Echo floor(93366/43200) . " months\n";
$rem = 93366%43200;
Echo floor($rem/1440) . " days\n";
$rem = $rem%1440;
Echo floor($rem/60) . " hours\n";
Echo $rem%60 . " minutes";
Output:
2 months
4 days
20 hours
6 minutes
https://3v4l.org/RreDY
Related
I have a little code just to know when a message was sent:
function time_ago ($respuestas) {
$date = $respuestas;
$today_date = getdate();
$months = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio','julio','agosto','septiembre','octubre','noviembre','diciembre'];
$minute = $today_date['minutes'];
$hour = $today_date['hours'];
$day = $today_date['mday'];
$month = $today_date['mon'];
if ($today_date['hours'] <= 9) {
$hour = "0" . $today_date['hours'];
}
if ($today_date['minutes'] <= 9) {
$minute = "0" . $today_date['minutes'];
}
if ($today_date['mon'] <= 9) {
$month = "0" . $today_date['mon'];
}
if ($today_date['mday'] <= 9) {
$day = "0" . $today_date['mday'];
}
$actual_total_date = $today_date['year'] . "-" . $month . "-" . $day . " " . $hour . ":" . $minute;
$actual_total_date = new DateTime($actual_total_date);
//data of the date of the post
$post_date = substr($date,0,16);
$post_date = new DateTime($post_date);
$post_year = substr($date,0,4);
$post_month = substr($date,5,2);
$post_day = substr($date,8,2);
$post_hour = substr($date,11,2);
$post_minute = substr($date,14,2);
$interval = date_diff($post_date, $actual_total_date);
$invertal_days = substr($interval->format('%R%a'),1,strlen($interval->format('%R%a')));
$invertal_hours = $interval->format('%H');
$invertal_minutes = $interval->format('%I');
$result = "";
if ($invertal_days == 0 AND $invertal_hours == 0 AND $invertal_minutes < 1) {
$result = "Now";
} else if ($invertal_days == 0 AND $invertal_hours == 0 AND $invertal_minutes == 1) {
$result = substr($invertal_minutes,1,2) . " minute ago";
} else if ($invertal_days == 0 AND $invertal_hours == 0 AND $invertal_minutes < 10 AND $invertal_minutes > 1) {
$result = substr($invertal_minutes,1,2) . " minutes ago";
} else if ($invertal_days == 0 AND $invertal_hours == 0 AND $invertal_minutes < 60 AND $invertal_minutes >= 10) {
$result = $invertal_minutes . " minutes ago";
} else if ($invertal_days == 0 AND $post_day == $day) {
$result = "Today at " . $post_hour . ":" . $post_minute ;
} else if ($invertal_days == 0 AND $post_day == $day-1) {
$result = "Yesterday at " . $post_hour . ":" . $post_minute;
} else if ($invertal_days == 1 AND $post_day == $day-1) {
$result = "Yesterday at " . $post_hour . ":" . $post_minute;
} else {
$result = $post_day . " " . $months[$post_month-1] . " " . $post_year . " " . $post_hour . ":" . $post_minute;
}
return $result;
The problem I'm having only happens in production, not in local, and after doing some research I don't know what is happening. What happens is that this function gives me two different outputs with the same input. For example with the date: 2017-07-09 20:52:39, at the time I'm sending this post, it should enter the fourth conditional, because the minutes interval is between 10 and 60 minutes.
I could share to the site where I'm having problems if needed. I have already tested the data I am using for the function and it is correct.
I'm needing help with trying to display the users last online time.
My aim is to make it so that if the users status is 'online', display last seen just now, else, display the last time they were seen. Or if it's better, just display their last online time including seconds.
My code works but for some reason, when the user is offline, it displays user last online 1 hour ago if it I logged out less than 10 seconds ago.
My code is below
//Our default online script to get the last active time period from our lastactive time
function time_since($since)
{
global $con;
global $user_infos;
foreach($user_infos as $user)
{
$last_active = $user[7];
$user_status = $user[6];
$chunks = array(
array(60 * 60 * 24 * 365 , 'year'),
array(60 * 60 * 24 * 30 , 'month'),
array(60 * 60 * 24 * 7, 'week'),
array(60 * 60 * 24 , 'day'),
array(60 * 60 , 'hour'),
array(60 , 'minute'),
array(1 , 'second')
);
for ($i = 0, $j = count($chunks); $i < $j; $i++)
{
$seconds = $chunks[$i][0];
$name = $chunks[$i][1];
if (($count = floor($since / $seconds)) != 0)
{
break;
}
}
$print = ($count == 1) ? '1 '.$name : "$count {$name}s";
$check = $user_status == 'online' ? 'last online just now' : 'last online '.$print;
return $check;
}
}
// I made to make it firstly, update the users lastactive time for each page they go on by calling the function user_online_check() in the header (which is called for every page)
// and secondly, make it return a green image if the client is online and a red image if the client is offline
function user_online_check()
{
global $con;
global $user_infos;
global $time;
foreach($user_infos as $user)
{
$username = $_SESSION["user_i"];
$now = date("Y-m-d H:i:s");
//mysqli_query($con, "UPDATE users SET lastactive = NOW() WHERE username = '$username'");
$last_active = $user[7];
$user_status = $user[6];
mysqli_query($con, "UPDATE users SET status = 'offline' WHERE TIMESTAMPDIFF(MINUTE, lastactive, NOW()) > 1 AND username = '$username' LIMIT 1");
mysqli_query($con, "UPDATE users SET status = 'online' WHERE TIMESTAMPDIFF(MINUTE, lastactive, NOW()) < 1 AND username = '$username' LIMIT 1");
if($user_status == 'online')
{
echo '<center><img src="images/user/bullet_green.ico" style="width: 20px; height: 20px;" title="'.time_since(time() - strtotime($last_active)).'"></center>';
}
else if($user_status == 'offline')
{
echo '<center><img src="images/user/bullet_red.ico" style="width: 20px; height: 20px;" title="'.time_since(time() - strtotime($last_active)).'"></center>';
}
}
}
try this
$seen = floor((time("now")-$row['time'])/60);
$more = false;
if($seen > 60) {
$more = true;
$hours = floor($seen/60);
$minutes = $seen-($hours*60);
if(($seen > 24) && ($more == true)) {
$days = floor(($seen/60)/24);
$hours = floor($seen/60)-($days*24);
}
if($minutes == 1) {
$minute = ' minute ';
} else {
$minute = ' minutes ';
}
if($hours == 1) {
$hour = ' hour ';
} else {
$hour = ' hours ';
}
if($days == 1) {
$day = ' day ';
} else {
$day = ' days ';
}
if($days > 0) {
$seen = $days . $day . $hours . $hour . $minutes . $minute . 'ago';
} else {
$seen = $hours . $hour . $minutes . $minute . 'ago';
}
} else {
if($seen == 1) {
$minute = ' minute ';
} else {
$minute = ' minutes ';
}
$seen = $seen . $minute . 'ago';
}
I am using a for loop to display numbers 1-60:
for($i=0; $i<=60; $i++)
within the loop, i want to be able to show the number of years and months. for example:
1 month
2 months
3 month
...
1 year
1 year 1 month
1 year 2 month
and so on...
i tried this:
if(!is_float($i/12)) {
$years = $i/12;
} else {
$years = 'no';
}
this shows 1 on the 12 month, 2 on 24 months but not the in between
You can use % and / for the integer part and the rest of division
try this loop for show the result
for($i=1; $i<=60; $i++){
echo 'year = ' . floor($i/12) . ' month = ' .$i%12 . '<br />';
}
I have used the following solution to complete my code with help from #scaisEdge
for($i=0; $i<=60; $i++) {
if(!is_float($i/12)) {
$years = floor($i / 12).' Year';
$years = $years.($years > 1 ? 's' : '');
if($years == 0) {
$years = '';
}
}
$months = ' '.($i % 12).' Month';
if($months == 0 or $months > 1) {
$months = $months.'s';
}
$display = $years.''.$months;
echo '<option value="'.$i.'"';
if($result["warrenty"] == $i) {
echo 'selected="selected"';
}
echo '>'.$display.'</option>';
}
function yearfm($months)
{
$str = '';
if(($y = round(bcdiv($months, 12))))
{
$str .= "$y Year".($y-1 ? 's' : null);
}
if(($m = round($months % 12)))
{
$str .= ($y ? ' ' : null)."$m Month".($m-1 ? 's' : null);
}
return empty($str) ? false : $str;
}
for($x = 0; $x < 100; $x++)
{
var_dump(yearfm($x));
}
another solution 1:
for ($i=0; $i<=60; $i++) {
$output = [];
if ($i >= 12) {
$years = ($i - $i % 12) / 12;
$output[] = $years > 1 ? $years . ' years' : $years . ' year';
}
if ($i % 12 > 0) {
$monthsRest = $i % 12;
$output[] = $monthsRest > 1 ? $monthsRest . ' months' : $monthsRest . ' month';
}
echo implode(' ', $output);
}
another solution 2:
for ($i=0; $i<=60; $i++) {
$output = [];
$startDate = new DateTime();
$endDate = new DateTime('+' . $i . ' months');
$interval = $startDate->diff($endDate);
$years = $interval->format('%y');
$months = $interval->format('%m');
if ($years > 0) {
$output[] = $years > 1 ? $years . ' years' : $years . ' year';
}
if ($months > 0) {
$output[] = $months > 1 ? $months . ' months' : $months . ' month';
}
echo implode(' ', $output);
}
I'm currently developing an android app which retrieve data from SQL database using PHP. Every set of data got difference timestamp. The format of the timestamp in my database is (yyyy-mm-dd h:m:s). Now i want convert my timestamp so Android user will see the timestamp like (X second ago, X minutes ago or X days ago). I tried in my php code but result i get from the timestamp for every set of data is (1 days ago). every set of data show 1 days ago. Can anyone help me? thanks
Product.php
<?php
$response = array();
// include db connect class
require_once 'include/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT *FROM image_detail ORDER BY posted_at DESC") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["uid"] = $row["uid"];
$product["itemname"] = $row["itemname"];
$product["price"] = $row["price"];
$product["description"] = $row["description"];
$product["path"] = $row["path"];
$timestamp = $row["posted_at"];
$now = date("Y-m-d h:i:s");
$product["posted_at"] = xTimeAgo($timestamp, $now, "x");
// push single product into final response array
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
function xTimeAgo ($oldTime, $newTime, $timeType) {
$timeCalc = strtotime($newTime) - strtotime($oldTime);
if ($timeType == "x") {
if ($timeCalc = 60) {
$timeType = "m";
}
if ($timeCalc = (60*60)) {
$timeType = "h";
}
if ($timeCalc = (60*60*24)) {
$timeType = "d";
}
}
if ($timeType == "s") {
$timeCalc .= " seconds ago";
}
if ($timeType == "m") {
$timeCalc = round($timeCalc/60) . " minutes ago";
}
if ($timeType == "h") {
$timeCalc = round($timeCalc/60/60) . " hours ago";
}
if ($timeType == "d") {
$timeCalc = round($timeCalc/60/60/24) . " days ago";
}
return $timeCalc;
}
?>
The code always returns one day because of this block of code:
if ($timeType == "x") {
if ($timeCalc = 60) {
$timeType = "m";
}
if ($timeCalc = (60*60)) {
$timeType = "h";
}
if ($timeCalc = (60*60*24)) {
$timeType = "d";
}
}
($timeCalc = 60) is not checking if $timeCalc is equal to 60, which is also wrong, it should check if it is greater than 60, it sets $timecalc to 60, which is also evaluated as true.
As a consequnce, every time you run the function, $timeCalc is first set to 60, then 60*60 and finally to 60*60*24. Likewise with $timeType, it is set to "m", then to "h" and finally to "d", and in this way, if you inspect your code, you see why it will always return one day.
Try setting the following if clauses instead:
if ($timeType == "x") {
if ($timeCalc > 60) {
$timeType = "m";
}
if ($timeCalc > (60*60)) {
$timeType = "h";
}
if ($timeCalc > (60*60*24)) {
$timeType = "d";
}
}
if ($timeType == "x") {
if ($timeCalc = 60) {
$timeType = "m";
}
if ($timeCalc = (60*60)) {
$timeType = "h";
}
if ($timeCalc = (60*60*24)) {
$timeType = "d";
}
}
You've got a proble here,
you affect $timeCalc in your if:
$timeCalc = 60
For exemple, i think you just forget == in all if.
Corrected code :
if ($timeType == "x") {
if ($timeCalc == 60) {
$timeType = "m";
}
if ($timeCalc == (60*60)) {
$timeType = "h";
}
if ($timeCalc == (60*60*24)) {
$timeType = "d";
}
}
The simplified script for same will be
function xTimeAgo ($oldTime, $newTime) {
$timeCalc = strtotime($newTime) – strtotime($oldTime);
if ($timeCalc > (60*60*24)) {$timeCalc = round($timeCalc/60/60/24) . ” days ago”;}
else if ($timeCalc > (60*60)) {$timeCalc = round($timeCalc/60/60) . ” hours ago”;}
else if ($timeCalc > 60) {$timeCalc = round($timeCalc/60) . ” minutes ago”;}
else if ($timeCalc > 0) {$timeCalc .= ” seconds ago”;}
return $timeCalc;
}
Try this. Hope this will help you.
There is a good example of code
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
Our CodeIgniter-based website has a section showing the last time a user logged in (using days if necessary and hrs, min, sec). I'm trying to make it print "day" when the result is 1 day and "days" when it is over 1 day. At the moment 1 day shows as 1 day but 2 days (and above) shows as 2 day 2 days. Can you see what I've done wrong here and modify the code?
$dDf = day
$hDf = hour
$mDf = minute
$sDf = second
<?php
if ($dDf < 1) {
if ($hDf > 0) {
if ($mDf < 0) {
$mDf = 60 + $mDf;
$hDf = $hDf - 1;
echo $mDf . ' min';
} else {
echo $hDf . ' hr ' . $mDf . ' min';
}
} else {
if ($mDf > 0) {
echo $mDf . ' min ' . $sDf . ' sec';
} else {
echo $sDf . ' sec';
}
}
} else {
echo $dDf . ' days ';
if ($dDf > 1) {
if ($hDf > 0) {
if ($mDf < 0) {
$mDf = 60 + $mDf;
$hDf = $hDf - 1;
echo $mDf . ' min';
} else {
echo $hDf . ' hr ' . $mDf . ' min';
}
} else {
if ($mDf > 0) {
echo $mDf . ' min ' . $sDf . ' sec';
} else {
echo $sDf . ' sec';
}
}
} else {
echo $dDf . ' day ';
if ($hDf > 0) {
if ($mDf < 0) {
$mDf = 60 + $mDf;
$hDf = $hDf - 1;
echo $mDf . ' min';
} else {
echo $hDf . ' hr ' . $mDf . ' min';
}
} else {
if ($mDf > 0) {
echo $mDf . ' min ' . $sDf . ' sec';
} else {
echo $sDf . ' sec';
}
}
}
}
?>
I was going to write something, but a very simple google search that lasted no more than 60 seconds came up with THIS, so there you have it. The code inside:
/**
* A function for making time periods readable
*
* #author Aidan Lister <aidan#php.net>
* #version 2.0.1
* #link http://aidanlister.com/2004/04/making-time-periods-readable/
* #param int number of seconds elapsed
* #param string which time periods to display
* #param bool whether to show zero time periods
*/
function time_duration($seconds, $use = null, $zeros = false)
{
// Define time periods
$periods = array (
'years' => 31556926,
'Months' => 2629743,
'weeks' => 604800,
'days' => 86400,
'hours' => 3600,
'minutes' => 60,
'seconds' => 1
);
// Break into periods
$seconds = (float) $seconds;
$segments = array();
foreach ($periods as $period => $value) {
if ($use && strpos($use, $period[0]) === false) {
continue;
}
$count = floor($seconds / $value);
if ($count == 0 && !$zeros) {
continue;
}
$segments[strtolower($period)] = $count;
$seconds = $seconds % $value;
}
// Build the string
$string = array();
foreach ($segments as $key => $value) {
$segment_name = substr($key, 0, -1);
$segment = $value . ' ' . $segment_name;
if ($value != 1) {
$segment .= 's';
}
$string[] = $segment;
}
return implode(', ', $string);
}
Is there a reason why you wouldn't want to use the built-in timespan() function for this?
<?php
$this->load->helper('date');
echo timespan($last_logged_in_timestamp);
I have an old example in my code library. It should give you an idea of how to do it.
function time_readable($duration) {
$days = floor($duration/86400);
$hrs = floor(($duration - $days * 86400) / 3600);
$min = floor(($duration - $days * 86400 - $hrs * 3600) / 60);
$s = $duration - $days * 86400 - $hrs * 3600 - $min * 60;
$return = ($days > 0) ? $days . ' d ' : '';
$return .= ($days > 0 || $hrs > 0) ? $hrs . ' hours ' : '';
$return .= ($days > 0 || $hrs > 0 || $min > 0) ? $min . ' min ' : '';
$return .= ($days > 0 || $hrs > 0 || $min > 0) ? $s . ' s ' : '';
return $return;
}