i've to display the differences between a column(reg_time) in mysql and the present time so that the final output (after some php to display in minutes or seconds or hours or days)
be:
Registered : 8 hours ago.
is there any function to do that?
thanks
//End date is current date
//$start_date, lets say sep 05 82 : 00:00:00
$seconds_dif = mktime(date("G"),date("i"),date("s"),date("m"),date("d"),date("Y")) - mktime('00','00','00','09','05','1982');
//Difference in seconds is $seconds_dif
//Now only math calculation to figure out months/years..
echo '<br />Years Difference = '. floor($seconds_dif/365/60/60/24);
echo '<br />Months Difference = '. floor($seconds_dif/60/60/24/7/4);
echo '<br />Weeks Difference = '. floor($seconds_dif/60/60/24/7);
echo '<br />Days Difference = '. floor($seconds_dif/60/60/24);
echo '<br />Hours Difference = '. floor($seconds_dif/60/60);
echo '<br />Minutes Difference = '. floor($seconds_dif/60);
Found here: http://www.webhostingtalk.com/showthread.php?t=453668
You need to edit the 3rd line of code for your data format:
mktime('00','00','00','09','05','1982')
Also you need to wrap this code into a function for easy using it:
/**
* Return string with date time difference between two arguments
* #param $start_date integer Start date in unix time (seconds from January 1 1970), you can use strtotime('24 November 2003 13:45:54'), for example
* #param $end_date integer [optional] End date in unix time, by default it equals now
* #return string
*/
function getDateTimeDifference($start_date, $end_date = time()) {
$end_date = mktime(date("G", $end_date),date("i", $end_date),date("s", $end_date),date("m", $end_date),date("d", $end_date),date("Y", $end_date));
$difference = $end_date - mktime(date("G", $start_date),date("i", $start_date),date("s", $start_date),date("m", $start_date),date("d", $start_date),date("Y", $start_date));
$years = floor($seconds_dif/365/60/60/24);
$months = floor($seconds_dif/60/60/24/7/4);
$weeks = floor($seconds_dif/60/60/24/7);
$days = floor($seconds_dif/60/60/24);
$hours = floor($seconds_dif/60/60);
$minutes = floor($seconds_dif/60);
$ret = 'Difference: ';
if (!empty($years))
$ret .= $years . ' years, ';
if (!empty($months))
$ret .= $months . ' months, ';
if (!empty($weeks))
$ret .= $weeks . ' weeks, ';
if (!empty($days))
$ret .= $days . ' days, ';
if (!empty($hours))
$ret .= $hours . ' hours, ';
if (!empty($minutes))
$ret .= $minutes . 'minutes';
return $ret;
}
Take a look at the MySQL functions timediff() (4.1.1+) and timestampdiff() (5.0+).
And the php method DateTime::diff() (5.3+)
e.g.
SELECT Now(), TIMESTAMPDIFF(HOUR, Now(), '2009-12-12 06:15:34')
just returned
"2009-12-12 12:34:00"; "-6"
on my machine. And
$dt = new DateTime('2008-03-18 06:15:34');
echo $dt->diff(new DateTime())->format('%y %d %h');
(currently) prints
1 25 6
Related
I want to get a user registered date, count the days since registration and show max days left to given days and show message after period ends.
What I got so far works:
$regDatestr = '2020-04-09 19:38:10';
$regDate = strtotime($regDatestr);
$regSince = time() - $regDate;
$days = round ($regSince / ( 60 * 60 * 24 ));
$maxDays = 20;
$maxDaysstr = strtotime("-$maxDays days");
$maxReg = ($regSince + $maxDaysstr);
$daysleft = time() - $maxReg;
$restDays = round ($daysleft / ( 60 * 60 * 24 ));
if ($regdate <= $maxDaysstr) :
echo 'period ended'
else :
echo 'Registered since' . $days . ' .days . Rest days ' . $restDays . '
endif;
$daysleft and days gives me the right days. But the period doesnt end exact after 20 days.
What I need is max 20 days since registration date. So when
'2020-04-09 19:38:10';
plus 20 days should end the period at
'2020-04-29 19:38:10';
but it seems my if condition doesnt work as expected. So Im getting "Registered since 21 days. Rest days 0".
Why is that so?
Because you have an typo in with your variable names
if ($regdate <= $maxDaysstr)
should be
if ($regDate <= $maxDaysstr)
and your code could be shorter
$regDatestr = '2020-04-01 19:38:10';
$regDate = new DateTime($regDatestr);
$diffToday = $regDate->diff(new DateTime());
$maxDays = 10;
$diffMax = $regDate->diff(new DateTime("-$maxDays days"));
if ($diffMax->invert == 0) :
echo 'period ended';
else :
echo 'Registered since ' . $diffToday->days . ' .days . Rest days ' . $diffMax->days;
endif;
I'm writing up a statistics script for a service I run. I want to work out the average number of rows per day on a last 3 days, weekly, monthly and yearly basis. My basic thought is something like this to grab the average:
<?php
function getDayNumber($day)
{
$start = strtotime("last monday");
$q = mysql_query(sprintf("SELECT COUNT(*) as count FROM mytable WHERE dayname(datetime) = "%s" AND unix_timestamp(datetime) > %s",$day,$start));
$row = mysql_fetch_assoc($q);
return $row['count'];
}
$monday = getDayNumber("Monday");
$tuesday = getDayNumber("Tuesday");
$wednesday = getDayNumber("Wednesday");
$thursday = getDayNumber("Thursday");
$friday = getDayNumber("Friday");
$average = ($monday+$tuesday+$wednesday+$thursday+$friday)/5;
?>
The above is just psuedo code written from my head. I can't think of a better method though.
Is this possible to do via nested/joined queries? I'll need to be able to do it on a daily, weekly, monthly... etc basis. I figure if I can find a way to pull all the data in MySQL, I can just add all the count(*)'s together and divide them via the number of responses.
Is this feasible?
Any help is appreciated - thanks all!
I suggest finding the date range for each data set then running your query. Hope this helps.
<?php
/**
* Get the average number of rows that were created
* during the given date range.
*
* #param string $range The date range to look for
* #return integer The average number of rows created in the given range
*/
function getAverageRows($range)
{
$date_begin = null;
$date_end = null;
switch($range)
{
case 'year':
// Calculate the beginning and end datetime of the past year
$date_begin = FIRST_DAY_OF_YEAR . ' 00:00:00';
$date_end = LAST_DAY_OF_YEAR . ' 23:59:59';
break;
case 'month':
// Calculate the beginning and end datetime of the past month
$date_begin = FIRST_DAY_OF_MONTH . ' 00:00:00';
$date_end = LAST_DAY_OF_MONTH . ' 23:59:59';
break;
case 'week':
// Calculate the beginning and end datetime of the past week
$date_begin = FIRST_DAY_OF_WEEK . ' 00:00:00';
$date_end = LAST_DAY_OF_WEEK . ' 23:59:59';
break;
default:
// Calculate the beginning and end datetime of the past three days
$date_begin = SEVENTY_SIX_HOURS_AGO;
$date_end = now();
break;
}
$query = "SELECT COUNT(*) FROM mytable WHERE datetime >= '{$date_begin}' AND datetime <= '{$date_end}'";
// Get and return query results
}
echo "Average Rows:<br/>";
echo "Past three days: " . getAverageRows() . "<br/>";
echo "Past week: " . getAverageRows('week') . "<br/>";
echo "Past Month: " . getAverageRows('month') . "<br/>";
echo "Past Year: " . getAverageRows('year') . "<br/>";
I have two dates in the mysql table.
sample:
date1: 2011-01-01 06:40:00
date2: 2011-02-19 18:00:00
I need to return the difference between them, like this:
50 days, 12 hours, 20 minutes
How can i do this in PHP or MYSQL?
This code should do what you need:
<?php
$result = mysql_query("SELECT (date1, date2) FROM myTable;");
while (list($date1, $date2) = mysql_fetch_array($result)) {
$firstdate = new DateTime($date1);
$seconddate = new DateTime($date2);
$diff = $firstdate->diff($seconddate);
echo $diff->d . " days, " . $diff->h . " hours, " . $diff->i . "minutes\n";
}
?>
try this,
SELECT CONCAT(
FLOOR(TIMESTAMPDIFF(HOUR,'2011-01-01 06:40:00', '2011-02-19 18:00:00') / 24), ' days ',
MOD(TIMESTAMPDIFF(HOUR,'2011-01-01 06:40:00', '2011-02-19 18:00:00'), 24), ' hours ',
MINUTE(TIMESTAMPDIFF(second,'2011-01-01 06:40:00', '2011-02-19 18:00:00')), ' minutes')
Check MySQL date calculations.
You can read about mysql DATEDIFF function: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_datediff
I'm trying to work with dates for the first time, I did it something about that with Flash but it's different.
I have two different dates and I'd like to see the difference in hours and days with them, I've found too many examples but not what I'm loking for:
<?php
$now_date = strtotime (date ('Y-m-d H:i:s')); // the current date
$key_date = strtotime (date ("2009-11-21 14:08:42"));
print date ($now_date - $key_date);
// it returns an integer like 5813, 5814, 5815, etc... (I presume they are seconds)
?>
How can I convert it to hours or to days?
The DateTime diff function returns a DateInterval object. This object consists of variabeles related to the difference. You can query the days, hours, minutes, seconds just like in the example above.
Example:
<?php
$dateObject = new DateTime(); // No arguments means 'now'
$otherDateObject = new DateTime('2008-08-14 03:14:15');
$diffObject = $dateObject->diff($otherDateObject));
echo "Days of difference: ". $diffObject->days;
?>
See the manual about DateTime.
Sadly, it's a PHP 5.3> only feature.
Well, you can always use date_diff, but that is only for PHP 5.3.0+
The alternative would be math.
How can I convert it [seconds] to hours or to days?
There are 60 seconds per minute, which means there are 3600 seconds per hour.
$hours = $seconds/3600;
And, of course, if you need days ...
$days = $hours/24;
If you dont have PHP5.3 you could use this method from userland (taken from WebDeveloper.com)
function date_time_diff($start, $end, $date_only = true) // $start and $end as timestamps
{
if ($start < $end) {
list($end, $start) = array($start, $end);
}
$result = array('years' => 0, 'months' => 0, 'days' => 0);
if (!$date_only) {
$result = array_merge($result, array('hours' => 0, 'minutes' => 0, 'seconds' => 0));
}
foreach ($result as $period => $value) {
while (($start = strtotime('-1 ' . $period, $start)) >= $end) {
$result[$period]++;
}
$start = strtotime('+1 ' . $period, $start);
}
return $result;
}
$date_1 = strtotime('2005-07-31');
$date_2 = time();
$diff = date_time_diff($date_1, $date_2);
foreach ($diff as $key => $val) {
echo $val . ' ' . $key . ' ';
}
// Displays:
// 3 years 4 months 11 days
TheGrandWazoo mentioned a method for php 5.3>. For lower versions you can devide the number of seconds between the two dates with the number of seconds in a day to find the number of days.
For days, you do:
$days = floor(($now_date - $key_date) / (60 * 60 * 24))
If you want to know how many hours are still left, you can use the modulo operator (%)
$hours = floor((($now_date - $key_date) % * (60 * 60 * 24)) / 60 * 60)
<?php
$now_date = strtotime (date ('Y-m-d H:i:s')); // the current date
$key_date = strtotime (date ("2009-11-21 14:08:42"));
$diff = $now_date - $key_date;
$days = floor($diff/(60*60*24));
$hours = floor(($diff-($days*60*60*24))/(60*60));
print $days." ".$hours." difference";
?>
I prefer to use epoch/unix time deltas. Time represented in seconds and as such you can very quickly divide by 3600 for hours and divide by 24*3600=86400 for days.
So, I have a field in my users table named last_active which updates every time a user reloads a page. It's stored in unix timestamp.
I would like to output it like this: Last online: 4 d 18 h 19 m ago
How would one do that? Can you do it with php's date()?
Thank you.
You could achieve this directly in MySQL if you like:
select date_format(from_unixtime(current_timestamp - last_timestamp),
'Last online: %e days, %k hours, %i minutes, %s seconds ago.');
(current_timestamp can be replaced with unix_timestamp(now()) if you want it calculated in-place)
DATE_FORMAT allows you to have a custom string based on a specific date. If you populate its date with the difference between two timestamps, it will work as you've asked.
The above solution will only work if it's under a month; if you want days of the year, use %j. The documentation for the function shows more.
The simplest approach to this is to take the last_active timestamp, and the current timestamp with time(). Then subtract the last active from the current timestamp, and then you simply divide the result with the amount of seconds in a day to get difference in days, amount of seconds in an hour to get difference in hours and so on.
This approach may be slightly inaccurate in some special cases (leap years, etc.) but it should suffice for your simpler usecase
After finding dozens of broken or half-there solutions, I built the following function for UNIX timestamps.
You can limit the detail level ...
echo timeDiff(1350297908); will show "5 minutes, 42 seconds ago".
echo timeDiff(1350297908, 1); will just show "5 minutes ago".
function timeDiff( $from, $levels=7 ){
$now = time();
$diff = ($from > $now) ? $from - $now : $now - $from;
$status = ($from > $now) ? ' away' : ' ago';
$times = array(31536000, 2628000, 604800, 86400, 3600, 60, 1);
$words = array('year', 'month', 'week', 'day', 'hour', 'minute', 'second');
$str = array();
foreach ($times as $k=>$v){
$val = floor($diff/$v);
if ($val) {
$str[] = $val .' '. $words[$k] . ($val==1 ? '' : 's');
$levels--;
}
$diff %= $v;
if ($levels==0) break;
}
return implode(', ', $str) . $status;
}
I wrote this simple function when I need this kind of solution (it gets minutes as input):
function minutes_to_time($minutes)
{
$obj = "";
// extract days
$days = floor($minutes/(1440)); # Divide on the daily minutes 60 min * 24 hours
# echo "Days: " . $days;
// extract hours
$hours = floor(($minutes-($days*1440))/60);
# echo " Hours: " . $hours;
// extract left minutes
$minutes = ($minutes-($days*24*60)-($hours*60));
# echo " Minutes: " . $minutes;
if ($days > 0)
{
$obj .= $days . "d ";
}
if ($hours > 0)
{
$obj .= $hours . "h ";
}
if ($minutes >= 0)
{
$obj .= $minutes . "m ";
}
$obj .= "ago";
return $obj;
}