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
Related
As per title, I'm trying to find the differance in seconds then covert these seconds to days and hours.
Having read and followed similar questions I have built a function that adds my desired hours, days, weeks, months or years to todays datetime and I am getting the correct result from that part of it.
However I then try and convert the two dates (start date and shifted date) to unix timestamps, subtract the two timestamps to find the difference between the two dates in seconds then convert to days or mins (/86400 and /3600) I am not getting the result I expected.
Here is the code..
<?php
$dateTimeNow = date();
function dateTimeShift($dateTimeIn, $lengthNum, $lengthWord) {
$shifted = date("Y-m-d H:i:s", strtotime($dateTimeIn." + $lengthNum $lengthWord"));
$difference = strtotime($shifted)-strtotime($dateTimeIn);
return $shifted . " <br> " . floor($difference/86400) . " days or " . floor($difference/3600) . " hours";
}
echo dateTimeShift($dateTimeNow, "1", "day");
?>
The result from this is currently..
2023-01-04 09:37:51 > 19361 days or 464673 hours
I expected it to be
2023-01-04 09:37:51 > 1 day or 24 hours
The problem is that you are using date() function without arguments, try with this one:
$dateTimeNow = date("Y-m-d H:i:s");
function dateTimeShift($dateTimeIn, $lengthNum, $lengthWord) {
$shifted = date("Y-m-d H:i:s", strtotime($dateTimeIn." + $lengthNum $lengthWord"));
$difference = strtotime($shifted)-strtotime($dateTimeIn);
return $shifted . " <br> " . floor($difference/86400) . " days or " . floor($difference/3600) . " hours";
}
echo dateTimeShift($dateTimeNow, "1", "day");
Output:
2023-01-04 09:57:31 <br> 1 days or 24 hours
I have been looking through all the previous questions which similar to this question unfortunately non of them work for me.
I am trying to get the number of weeks between two dates.
$result = mysqli_query($con,"SELECT * FROM `test` WHERE `DateofTest` BETWEEN '" .
$startDate . "' AND '" . $endDate . "' ") or die ("Error: ".mysqli_error($con));
$startDate = $_POST['start'];
$endDate = $POST['end'];
Suppose my start date is 01/12/2014 and end date is 31/12/2014 so 4 weeks.
Here is my code
$startDate ="2014-12-01";
$endDate ="2014-12-31";
$days=($startDate - $endDate);
echo $days;
$weeks=($days / 7);
echo $weeks;
I am getting 0 result for each days and weeks.
Any ideas please.
Thanks
Something like this using the date time object will work
$d1 = new DateTime("2014-12-01");
$d2 = new DateTime("2014-12-31");
$difference_in_days = $d1->diff($d2)->days;
echo "Diff in Weeks = ".$difference_in_days/7;
You can't calculate strings. You need to convert them to dates.
You can do something like:
function get_number_of_weeks($startDate, $endDate) {
// use strtotime and substract the end date from the start date, not the otherway around
$days = strtotime($endDate) - strtotime($startDate);
// devide by seconds / hours and weeks
$weeks = $days / 3600 / 24 / 7;
// floor the amount of weeks.
return floor($weeks);
}
echo get_number_of_weeks("2014-12-01", "2014-12-31");
You cannot compare date strings and expect to get the difference.
You should use the DateTime class to compare two datetime values:
$startDate = new DateTime("2014-12-01");
$endDate = new DateTime("2014-12-31");
$diff = $startDate->diff( $endDate )->format('%d');
$weeks = floor($diff/7);
format method can return a difference in a number of ways like years/months/days/hours/minutes/seconds. More here
Try this..
<?php
$d1 ="2014-12-01";
$d2 ="2014-12-31";
$diffweek = abs(strtotime($d1) - strtotime($d2)) / 604800;
echo round($diffweek); or echo intval($diffweek);
?>
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
How would I check if a date in the format "2008-02-16 12:59:57" is less than 24 hours ago?
if (strtotime("2008-02-16 12:59:57") >= time() - 24 * 60 * 60)
{ /*LESS*/ }
Just adding another answer, using strtotime's relative dates:
$date = '2008-02-16 12:59:57';
if (strtotime("$date +1 day") <= time()) {
// Do something
}
I think this makes the code much more readable.
if ((time() - strtotime("2008-02-16 12:59:57")) < 24*60*60) {
// less than 24 hours ago
}
e.g. via strtotime and time().
The difference must be less then 86400 (seconds per day).
<?php
echo 'now: ', date('Y-m-d H:i:s'), "\n";
foreach( array('2008-02-16 12:59:57', '2009-12-02 13:00:00', '2009-12-02 20:00:00') as $input ) {
$diff = time()-strtotime($input);
echo $input, ' ', $diff, " ", $diff < 86400 ? '+':'-', "\n";
}
prints
now: 2009-12-03 18:02:29
2008-02-16 12:59:57 56696552 -
2009-12-02 13:00:00 104549 -
2009-12-02 20:00:00 79349 +
only the last test date/time lays less than 24 hours in the past.
Php has a comparison function between two date/time objects, but I don't really like it very much. It can be imprecise.
What I do is use strtotime() to make a unix timestamp out of the date object, then compare it with the output of time().
Just use it.....
if(strtotime($date_start) >= strtotime($currentDate))
{
// Your code
}
Maybe it will be more easy to understand...
$my_date = '2008-02-16 12:59:57';
$one_day_after = date('Y-m-d H:i:s', strtotime('2008-02-16 12:59:57 +1 days'));
if($my_date < $one_day_after) {
echo $my_date . " is less than 24 hours ago!";
} else {
echo $my_date . " is more than 24 hours ago!";
}
There should be you variable date Like
$date_value = "2013-09-12";
$Current_date = date("Y-m-d"); OR $current_date_time_stamp = time();
You can Compare both date after convert date into time-stamp so :
if(strtotime($current_date) >= strtotime($date_value)) {
echo "current date is bigger then my date value";
}
OR
if($current_date_time_stamp >= strtotime($date_value)) {
echo "current date is bigger then my date value";
}
You can use Simple PHP to do this:
$date = new simpleDate();
echo $date->now()->subtractHour(24)->compare('2008-02-16 12:59:57')->isBefore();
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;
}