I'm creating a countdown for how long people can do specific functions on a specific page. I've made a countdown, but he is going under 0, so he's counting further negatively.
I'm printing out the countdown like this:
-4 days -10 h -3 m -34 s remaining to run 1210 meter
My countdown,
$Date = "" . $groups['group_date'] . "";
$stopDate = date('Y-m-d H:i:s', strtotime($Date. ' +' . $periodOfRunning . 'days'));
<h3><?php $rem = strtotime($stopDate) - time();
$day = floor($rem / 86400);
$hr = floor(($rem % 86400) / 3600);
$min = floor(($rem % 3600) / 60);
$sec = ($rem % 60);
if($day) echo "$day days ";
if($hr) echo "$hr h ";
if($min) echo "$min m ";
if($sec) echo "$sec s";
echo " remaining to run " . $totalDistanceToDo . " meter";
?></h3>
If you use DateTime() you can compare the two times and see if the stop time is in the past. If it is, display a different message. Also, this makes getting the interval between the two easier to get and display:
$now = new DateTime();
$stopdate = new DateTime($stopDate);
if ($stopdate > $now) {
$diff = $now->diff($stopTime);
echo $diff->format('%d days, %h hours, %i minutes, %s seconds');
echo " remaining to run " . $totalDistanceToDo . " meter";
}
else {
// negative time. display something else
}
Keep in mind if you don't want to display zero values for time units it will be a little more complex:
$now = new DateTime();
$stopdate = new DateTime($stopDate);
if ($stopdate > $now) {
$diff = $now->diff($stopTime);
if ($diff->d > 0) echo $diff->d . ' days, ';
if ($diff->h > 0) echo $diff->h . ' hours, ';
if ($diff->i > 0) echo $diff->i . ' minutes, ';
if ($diff->s > 0) echo $diff->s . ' seconds';
echo " remaining to run " . $totalDistanceToDo . " meter";
}
else {
// negative time. display something else
}
Related
Hi I'm making an online coupon system for mobile devices. The coupons are for a limited time active and I have to do a check on the coupons. I use date(d/m/Y H:i:s) for just showing the date and time, and I also have a expire date which is a just a string that I later convert into a date.
This is how I do the check if the coupon is expired:
if ($date1B > $date2B) {
echo "<script>alert('Expired coupon!!');</script>";
}
Now what I want is to calculate the days when the coupon will be expired.
This is what I found on W3Schools, but the example below uses date_create(), so you make an custom date and time. I already have 2 dates and times.
$date1 = date("d-m-Y H:i:s");
$date2 = date_format($date2A, 'd-m-Y H:i:s');
$diff = date_diff($date1,$date2);
echo $diff->format("%a days %h Hours %i Minute %s Seconds ");
When I replace variables with the existing variables I get these errors:
date_diff() expects parameter 1 to be DateTimeInterface, string given in
and
Call to a member function format() on boolean in
The full .PHP page:
<?php
date_default_timezone_set("America/Curacao");
$date1A = date("d/m/Y H:i:s");
$date1B = date("dmYHis");
$date2B = "27032017042100";
$date2A = date_create_from_format('dmYHis', $date2B);
echo "Datum 1: " . $date1A . "<br>" ;
echo "Datum 1: " . $date1B . "<br><br>";
echo "Datum 2: " . date_format($date2A, 'd/m/Y H:i:s') . "<br>";
echo "Datum 2: " . $date2B . "<br>";
if ($date1B > $date2B) {
echo "<script>alert('Klaar!!');</script>";
}
$date1 = date("d/m/Y H:i:s");
$date2 = date_format($date2A, 'd/m/Y H:i:s');
$diff = date_diff($date1,$date2);
echo $diff->format("%a days %h Hours %i Minute %s Seconds ");
?>
Updated .PHP file
I fixed the errors.. This is the updated .PHP page:
<?php
date_default_timezone_set("America/Curacao");
$date1A = date("d-m-Y H:i:s");
$date1 = date_create($date1A);
echo date_format($date1,"d-m-Y H:i:s");
echo "<br>";
$date2B = "31032017042100";
$date2A = date_create_from_format('dmYHis', $date2B);
$final = date_format($date2A, 'd-m-Y H:i:s');
$date2 = date_create($final);
echo date_format($date2,"d-m-Y H:i:s");
echo "<br>";
$diff = date_diff($date1, $date2);
echo $diff->format("%R %a days %h Hours %i Minute %s Seconds");
if ($date1 > $date2) {
echo "<script>alert('Coupon Expired!!');</script>";
}
?>
The simplest way to calculate the difference between two dates is date_diff() function which gives error on invalid dates.
Before passing on the values to date_diff function you should use the date_create() function.
Usage:
<?php
$startDate = date_create('2014-06-13');
$endDate = date_create('2017-08-10');
$diff = date_diff($startDate, $endDate);
var_export($diff);
Which gives you output like:
DateInterval::__set_state(array( 'y' => 3, 'm' => 1, 'd' => 28, 'h' => 0, 'i' => 0, 's' => 0, 'weekday' => 0, 'weekday_behavior' => 0, 'first_last_day_of' => 0, 'invert' => 0, 'days' => 1154, 'special_type' => 0, 'special_amount' => 0, 'have_weekday_relative' => 0, 'have_special_relative' => 0, ))
UPDATE
You can use or modify the following function to get the difference:
function dateDifference($startDate, $endDate)
{
try {
$startDate = date_create($startDate);
$endDate = date_create($endDate);
$diff = date_diff($startDate, $endDate);
$d = "";
if ($diff->y != 0) {
if ($diff->y > 1) {
$d .= $diff->y . " Years ";
} else {
$d .= $diff->y . " Year ";
}
}
if ($diff->m != 0) {
if ($diff->m > 1) {
$d .= $diff->m . " Months ";
} else {
$d .= $diff->m . " Month ";
}
}
if ($diff->d != 0) {
if ($diff->d > 1) {
$d .= $diff->d . " Days ";
} else {
$d .= $diff->d . " Day ";
}
}
if ($diff->h != 0) {
if ($diff->h > 1) {
$d .= $diff->h . " Hours ";
} else {
$d .= $diff->h . " Hour ";
}
}
if ($diff->i != 0) {
if ($diff->i > 1) {
$d .= $diff->i . " Minutes ";
} else {
$d .= $diff->i . " Minute ";
}
}
if ($diff->s != 0) {
if ($diff->s > 1) {
$d .= $diff->s . " Seconds ";
} else {
$d .= $diff->s . " Second ";
}
}
return $d;
}
catch(Exception $e)
{
die("ERROR");
}
}
Running it like so:
echo dateDifference('2014-10-16', '2017-06-08');
shall output:
2 Years 7 Months 23 Days
Based on #ShaktiPhartiyal answer, to output in the format that you want, just use:
$startDate = date_create('2014-06-13');
$endDate = date_create('2017-08-10');
$diff = date_diff($startDate, $endDate);
echo $diff->format("%a days %h Hours %i Minute %s Seconds ");
And the output will be:
1154 days 0 Hours 0 Minute 0 Seconds
I know this question has been asked several times and I found so many tutorials, blog posts about converting timestamp to ago time in php..
I have tried countless codes and nothing seems to work for me...
I either get a blank page with no errors (i have error rerposting on my php page), or I get some strange numbers in my page..
so I thought someone here could shed a light on this for me..
Basically I am saving date like so:
$date = date('Y-m-d H:i:s');
I simply save it in mysql database...
and I echo it like so:
echo $date;
so now what I need to know is how I can convert the echo $date; to something like 1 minutes ago, 10 minutes ago, 1 hour ago etc etc every time the page closes and reopens?
I did try so many functions that I found on google and noon seem to do anything!
could someone please advise on this issue?
Thanks
EDIT:
I used this code as stated in the answer but I still get the $date echo-ed exactly the same way as its stored in the database which is this format: 2014-10-06 22:54:54
$date = date('Y-m-d H:i:s');
$time1 = new DateTime($date);
$now = new DateTime();
$interval = $time1->diff($now);
if ($interval->y) $date = $interval->y . ' years';
elseif ($interval->m) $date = $interval->m . ' months';
elseif ($interval->d) $date = $interval->d . ' days';
elseif ($interval->h) $date = $interval->h . ' hours';
elseif ($interval->i) $date = $interval->i . ' minutes';
echo $date;
You should use the DateTime class to get the difference between 2 times, ie;
$time1 = new DateTime('2014-10-06 09:00:59');
$now = new DateTime();
$interval = $time1->diff($now,true);
and then use that difference (which is a DateInterval object, $interval) to find the smallest time difference like this;
if ($interval->y) echo $interval->y . ' years';
elseif ($interval->m) echo $interval->m . ' months';
elseif ($interval->d) echo $interval->d . ' days';
elseif ($interval->h) echo $interval->h . ' hours';
elseif ($interval->i) echo $interval->i . ' minutes';
else echo "less than 1 minute";
which should echo (at time of writing) 13 hours.
Hope this helps.
Check this function intval() - http://php.net/manual/en/function.intval.php
The following code should help you out
$seconds_ago = (time() - strtotime('2014-01-06 15:25:08'));
if ($seconds_ago >= 31536000) {
echo "Seen " . intval($seconds_ago / 31536000) . " years ago";
} elseif ($seconds_ago >= 2419200) {
echo "Seen " . intval($seconds_ago / 2419200) . " months ago";
} elseif ($seconds_ago >= 86400) {
echo "Seen " . intval($seconds_ago / 86400) . " days ago";
} elseif ($seconds_ago >= 3600) {
echo "Seen " . intval($seconds_ago / 3600) . " hours ago";
} elseif ($seconds_ago >= 60) {
echo "Seen " . intval($seconds_ago / 60) . " minutes ago";
} else {
echo "Seen less than a minute ago";
}
I have a timestamp and would like to show my users... last sent 1 day, 23 hours, 54 minutes, and 33 seconds ago. I know how to get the difference in time...
$timePast = '2012-08-18 22:11:33';
$timeNow = date('Y-m-d H:i:s');
// gives total seconds difference
$timeDiff = strtotime($timeNow) - strtotime($timePast);
Now I am stuck not being able to show the time like above.
x day, x hours, x mins, x seconds where all the x's should add up to the total seconds time difference. I know the following...
$lastSent['h'] = round($timeDiff / 3600);
$lastSent['m'] = round($timeDiff / 60);
$lastSent['s'] = $timeDiff;
Need you help! Thanks in advance.
After this:
$timeDiff = strtotime($timeNow) - strtotime($timePast);
add:
if ($timeDiff > (60*60*24)) {$timeDiff = floor($timeDiff/60/60/24) . ' days ago';}
else if ($timeDiff > (60*60)) {$timeDiff = floor($timeDiff/60/60) . ' hours ago';}
else if ($timeDiff > 60) {$timeDiff = floor($timeDiff/60) . ' minutes ago';}
else if ($timeDiff > 0) {$timeDiff .= ' seconds ago';}
echo $timeDiff;
Don't do date math manually!
PHP can work out all of the date/time math for you, using the DateTime and DateInterval classes.
Getting an interval between two dates
$timePast = new DateTime('2012-08-18 22:11:33');
$timeNow = new DateTime;
$lastSent = $timePast->diff($timeNow);
// $lastSent is a DateInterval with properties for the years, months, etc.
Formatting example
A function for getting a formatted string might look like the following (though this is only one super-basic way, of many).
function format_interval(DateInterval $interval) {
$units = array('y' => 'years', 'm' => 'months', 'd' => 'days',
'h' => 'hours', 'i' => 'minutes', 's' => 'seconds');
$parts = array();
foreach ($units as $part => $label) {
if ($interval->$part > 0) {
$parts[] = $interval->$part . ' ' . $units[$part];
}
}
return implode(', ', $parts);
}
echo format_interval($lastSent); // e.g. 2 days, 24 minutes, 46 seconds
I took Kalpesh's code and made it work by using floor instead of round and by calculating the different frictions of the day. Here it goes:
function timeAgo ($oldTime, $newTime) {
$timeCalc = strtotime($newTime) - strtotime($oldTime);
$ans = "";
if ($timeCalc > 60*60*24) {
$days = floor($timeCalc/60/60/24);
$ans .= "$days days";
$timeCalc = $timeCalc - ($days * (60*60*24));
}
if ($timeCalc > 60*60) {
$hours = floor($timeCalc/60/60);
$ans .= ", $hours hours";
$timeCalc = $timeCalc - ($hours * (60*60));
}
if ($timeCalc > 60) {
$minutes = floor($timeCalc/60);
$ans .= ", $minutes minutes";
$timeCalc = $timeCalc - ($minutes * 60);
}
if ($timeCalc > 0) {
$ans .= "and $timeCalc seconds";
}
return $ans . " ago";
}
$timePast = '2012-08-18 22:11:33';
$timeNow = date('Y-m-d H:i:s');
$t = timeAgo($timePast, $timeNow);
echo $t;
Output:
1 days, 16 hours, 11 minutes and 18 seconds ago
You'll need a lot of if's, the modulus (%), floor() (not round())
Or Google ;-)
I have used many functions for relative time in php but that give different results...help me
My functions :
<?php
function pretty_relative_time($time) {
if ($time !== intval($time)) { $time = strtotime($time); }
$d = time() - $time;
if ($time < strtotime(date('Y-m-d 00:00:00')) - 60*60*24*3) {
$format = 'F j';
if (date('Y') !== date('Y', $time)) {
$format .= ", Y";
}
return date($format, $time);
}
if ($d >= 60*60*24) {
$day = 'Yesterday';
if (date('l', time() - 60*60*24) !== date('l', $time)) { $day = date('l', $time); }
return $day . " at " . date('g:ia', $time);
}
if ($d >= 60*60*2) { return intval($d / (60*60)) . " hours ago"; }
if ($d >= 60*60) { return "about an hour ago"; }
if ($d >= 60*2) { return intval($d / 60) . " minutes ago"; }
if ($d >= 60) { return "about a minute ago"; }
if ($d >= 2) { return intval($d) . " seconds ago"; }
else {return "Just Now"; }
}
function plural($num) {
if ($num != 1)
return "s";
}
function getRelativeTime($date) {
$diff = time() - strtotime($date);
if ($diff<60)
return $diff . " second" . plural($diff) . " ago";
$diff = round($diff/60);
if ($diff<60)
return $diff . " minute" . plural($diff) . " ago";
$diff = round($diff/60);
if ($diff<24)
return $diff . " hour" . plural($diff) . " ago";
$diff = round($diff/24);
if ($diff<7)
return $diff . " day" . plural($diff) . " ago";
$diff = round($diff/7);
if ($diff<4)
return $diff . " week" . plural($diff) . " ago";
return "on " . date("F j, Y", strtotime($date));
}
echo pretty_relative_time('2012-08-06 8:04:15') ;echo "<br/>";
echo getRelativeTime('2012-08-06 8:04:15');
?>
OutPut :
Just Now // for first function
-15747 seconds ago // for second function
any settings in db ?.....i have used DATETIME for date...
You haven't made clear what output you're expecting, but from your later comment it should be "1 hour ago"? In which case I suspect you are suffering from timezone problems - most likely the dreaded "Daylight Savings Time". Try echoing date('Y-m-d H:i:s') in PHP and seeing if it comes out with the value you expect.
The discrepancy could be in the timezone set in php.ini, or the system clock of the webserver itself, not matching the timezone setting of the database, or the system clock on that server.
I have a php timestamp 1331875634 generated using php time() function.
I have the current timestamp generated using same function.
<?php
$time1 = "1331875634";
$time2 = time();
echo $differencem; //time difference in minutes
echo $differenceh; //time difference in hours
?>
I want to know the difference between these two in minutes. The minutes may be divided by 60 to make it in hours.
You get the different in seconds if you subtract them, so divide it by 60 to get minutes and by 60 again to get hours.
I created this code to take standard PHP UNIX TIMESTAMP, calculate the difference in time and return a standard time or a specialized time format. This is great for timing a project and calculating the time it takes to get the results.
function timerFormat($start_time, $end_time, $std_format = false)
{
$total_time = $end_time - $start_time;
$days = floor($total_time /86400);
$hours = floor($total_time /3600);
$minutes = intval(($total_time/60) % 60);
$seconds = intval($total_time % 60);
$results = "";
if($std_format == false)
{
if($days > 0) $results .= $days . (($days > 1)?" days ":" day ");
if($hours > 0) $results .= $hours . (($hours > 1)?" hours ":" hour ");
if($minutes > 0) $results .= $minutes . (($minutes > 1)?" minutes ":" minute ");
if($seconds > 0) $results .= $seconds . (($seconds > 1)?" seconds ":" second ");
}
else
{
if($days > 0) $results = $days . (($days > 1)?" days ":" day ");
$results = sprintf("%s%02d:%02d:%02d",$results,$hours,$minutes,$seconds);
}
return $results;
}
Example:
$begin_routine_time = time();
echo(timerFormat($begin_routine_time, $time()));
$datetime1 = new DateTime(date('Y-m-d H:i:s', 1331875634));
$datetime2 = new DateTime(date('Y-m-d H:i:s'));
$oDiff = $datetime1->diff($datetime2);
echo $oDiff->y.' Years <br/>';
echo $oDiff->m.' Months <br/>';
echo $oDiff->d.' Days <br/>';
echo $oDiff->h.' Hours <br/>';
echo $oDiff->i.' Minutes <br/>';
echo $oDiff->s.' Seconds <br/>';
Once I needed to convert seconds to time like 1 day 03:34:13 days hours:minuts:secondes
I wrote this function
function sECONDS_TO_HMS($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_HMS(65); // 00:01:05
echo sECONDS_TO_HMS(76325); //21:12:05
echo sECONDS_TO_HMS(345872); // 4 Days 00:04:32
I think it could be helpful for you.