Currently I have the following string.
$timeago = human_time_diff( get_the_time('U'), current_time('timestamp') );
print $timeago;
This returns results that looks like this.
1 min, 1 hour, 1 week, 1 month, and 1 year.
I am trying to figure out how I can make this work using an if statement to detect if the post has been posted within the past 5 hours, and if it has make it echo "NEW" but if not, don't echo anything.
EDIT:
I tried the following with no success... I am getting confused on how to make it check for the hours portion as well as the number portion I guess.
$timeago = human_time_diff( get_the_time('U'), current_time('timestamp') );
print $timeago;
if( $timeago >= 0 && $timeago <= 5 )
{
print 'NEW';
}
You have to do it manually like below:
$from = current_time('timestamp') - 1000000;
$to = current_time('timestamp');
$diff = (int) abs($to - $from);
$hours = round($diff / HOUR_IN_SECONDS);
if ($hours <= 1)
$hours = 1;
echo $hours; //OP = 278 (278 hours)
Related
This question already has answers here:
How do I find the hour difference between two dates in PHP?
(10 answers)
Closed 5 years ago.
I have datetimes in the following format:
Start: 2017-07-16 20:00
End: 2017-07-16 23:30
Start: 2017-07-18 21:30
End: 2017-07-19 00:30
I need to tell from these intervals how many hours (in 0,5 increments) are spent between 18:00-22:00 and 22:00-06:00 in total for a month.
Thanks in advance for any hint.
The current code I have is this, but I'm not sure if it is covering all timeframe possibilities:
<?php
date_default_timezone_set("UTC");
$start = array(
"2017-07-16 21:30:00",
"2017-07-16 18:00:00"
);
$end = array(
"2017-07-17 00:30:00",
"2017-07-16 18:30:00"
);
$amount_low = 0;
$amount_high = 0;
for($i = 0; $i < sizeof($start); $i++) {
$start_time = date("H:i:s", strtotime($start[$i]));
$end_time = date("H:i:s", strtotime($end[$i]));
$start_date = date("Ymd", strtotime($start[$i]));
$end_date = date("Ymd", strtotime($end[$i]));
// getting chunk before 22:00 if
if(
(strtotime($start[$i]) >= strtotime($start_date . " 18:00") && strtotime($start[$i]) < strtotime($start_date . " 22:00"))
&&
$start_date < $end_date
) {
$interval_low = strtotime($start_date . " 22:00") - strtotime($start[$i]);
$amount_low += ceil($interval_low / 1800) / 2;
}
//amount_high
if(strtotime($start[$i]) > strtotime($start_date . " 22:00") && strtotime($start[$i]) < strtotime($start_date . " 06:00")) {
$interval_high = strtotime($end[$i]) - strtotime($start[$i]); //needs further things
$amount_high += ceil($interval_high / 1800) / 2;
} elseif (strtotime($start[$i]) < strtotime($start_date . " 22:00") && strtotime($end[$i]) > strtotime($start_date . " 22:00")) {
$interval_high = strtotime($end[$i]) - strtotime($start_date . " 22:00");
$amount_high += ceil($interval_high / 1800) / 2;
} else {
$interval_low = strtotime($end[$i]) - strtotime($start[$i]);
$amount_low += ceil($interval_low / 1800) / 2;
}
}
echo $amount_low;
echo "\n$amount_high";
?>
Would this work for you?
$start = strtotime('2017-07-16 20:00');
$end = strtotime('2017-07-16 23:30');
$interval = $end - $start;
$hours = floor($interval / 1800)/2;
echo($hours);
This will display the total hours (in 0,5 increments) between the two dates (rounding down, so if it's 55 minutes, it's 0,5 hours; replace 'floor' with 'ceil' for the opposite).
I believe a part of your solution is found here from Aillyn
You can convert them to timestamps and go from there:
$hourdiff = round((strtotime($time1) - strtotime($time2))/3600, 1);
Dividing by 3600 because there are 3600 seconds in one hour and using round()
to avoid having a lot of decimal places.
$hourdiff = round((strtotime($time1) - strtotime($time2))/3600, 1);
This will give you a rounded hour difference between the two times. You could do something similar, just apply it for each interval for which ever month and adjust your math. There's not really going to be a single PHP function you can call to solve this.
Here is a PHP function I have designed, which is supposed to determine the amount of time passed in secs,mins,hours,days,weeks,months, and years - depending upon which bracket it is beneath. However Ive noticed that the values being returned seem to increase faster than actual time (within 30 mins, it outputs "1 weeks ago"). Im wondering if $time is actually in millis? That said, for the first 2 mins it outputs relatively accurate results.
Note: Running on 1and1 host.
Here's the function:
function get_relative_date($conn,$date,$post_id){
#get current timestamp
$q = "SELECT NOW() - INTERVAL 1 HOUR - `timestamp` FROM `posts` WHERE id=".$post_id.";";
# - INTERVAL 1 HOUR added due to server running 1 hour ahead.
$result = mysqli_query($conn,$q);
if ($result != null && $result != false){
$row = mysqli_fetch_array($result,MYSQLI_BOTH);
$time = $row[0]; #time passed since post
$min = 60;
$hour = $min*60;
$day = $hour*24;
$week = $day*7;
$month = $week*4;
$year = $month*12;
if ($time < $min){
return $time." secs ago";
}
if ($time < $hour){
return round(($time / $min))." mins ago";
}
if ($time < $day){
return round(($time / $hour))." hours ago";
}
if ($time < $week){
return round(($time / $day))." days ago";
}
if ($time < $month){
return round(($time / $week))." weeks ago";
}
if ($time < $year){
return round(($time / $month))." months ago";
}
if ($time >= $year){
return round(($time / $year))." years ago.";
}
return false;
}
}
Cheers.
I tried your query out and instead of 2 minutes and 40 seconds (in seconds) I was receiving 240 and instead of 1 hour 3 minutes and 40 seconds (in seconds) I got 10340.
You need this:
SELECT TIME_TO_SEC(TIMEDIFF(NOW(),`timestamp`)) FROM `posts` ...
This will select the time difference in seconds and hopefully give you the desired result.
I am using the following code to calculate the days remaining to make edits. They have 30 days to make edits, and days count down, this code works perfectly.
<?php
// Calculate days remains to edit or change details
$today = time();
$cdate = strtotime($row_details['payment_date']);//strtotime("19:19:09 Sep 27, 2011");
$dateDiff = $today - $cdate;
$fullDays = floor($dateDiff/(60*60*24));
$dayscalculate = 30 - $fullDays; // Set number of days
echo $dayscalculate.(($dayscalculate == 1) ? " day" : " days");
//
?>
QUESTION: if days = say 3 will say 3 days.. but if days = 0 (is the last of the 30 days).. Then want to say this is your last day or something.. So need an if based on $dayscalculate..
Ideas?
Thank you
How about...
if ($dayscalculate == 0) {
echo 'This is your last day';
} else {
printf('%d day%s',
$dayscalculate,
$dayscalculate > 1 ? 's' : ''
);
}
You may also want to introduce an "out of time" check, ie $dayscalculate < 0 but then again, you may already be handling this scenario.
I'm creating an application for a friend to handle Deadlines. I have a page set up where each user can see their own 'jobs to do' with a deadline next to it. My question is...
How do I compare a deadline date that comes back from the mysql query as 2010.08.08 with today's date?
For Example...
<?php
while($row = mysql_fetch_array($result)){
$jobfinishdate = $row['jobfinishdate'];
$date = date('Y-m-d');
if ($jobfinishdate>$date)
$jobfinishdate .= " - Not due yet!" ;
else if ($jobfinishdate<$date)
$jobfinishdate .= " - You didn't meet this deadline!";
else if ($jobfinishdate==$date)
$jobfinishdate .= " - Deadline is TODAY!";
}
?>
This works ok. But what I'd really like to do is display a message saying 'you have 5 days until deadline. Any ideas how to get around this?
Thanks.
Shane.
If possible I would let the database return the number of days, with a query like this:
SELECT jobfinishdate, datediff(jobfinishdate, NOW() AS days) FROM table
Then use this number of days:
while ($row = mysql_fetch_array($result)){
$jobfinishdate = $row['jobfinishdate'];
$days = $row['days'];
if ($days > 0) {
$jobfinishdate .= " - Not due yet! $days until deadline" ;
} elseif ($days < 0) {
$jobfinishdate .= " - You didn't meet this deadline!";
} else {
$jobfinishdate .= " - Deadline is TODAY!";
}
}
Some other remarks:
If you keep the date calculation in PHP, move the $date declaration outside the while loop because you only need to do that once.
you can remove the last condition, if ($jobfinishdate==$date). If the date is not larger and not smaller, it can only be equal.
$days = (strtotime($jobfinishdate) - strtotime($date)) / (60 * 60 * 24);
Should get you the amount of days left on the deadline.
Edit: The above will always return the difference in days - to handle whether or not its before or beyond the due date, maybe (using just time() as Adam suggested):
$date_passed = false;
$days = strtotime($jobfinishdate) - time();
if ($days < 0) { $date_passed = true; }
$days = $days / (60 * 60 * 24);
if (!$date_passed)
{
echo "You have $days days left on this project.";
}
else
{
echo "Deadline has expired $days days ago.";
}
// calculate days left
$daysleft = round( ( strtotime( $jobfinishdate ) - time() ) / 86400 );
// print out text for $daysleft
if( $daysleft == 0 )
print( "Deadline is today!" );
else if ( $daysleft > 0 )
printf( "You have %d days until deadline.", $daysleft );
else
print( "You did not meet the deadline!" );
If you're using PHP 5.3.0 or newer you can use the DateTime object
In SQL query:
SELECT
...,
TIMESTAMPDIFF(DAY, NOW(), `date_deadline`) AS days_to_deadline
...
This will produce positive number of days due deadline and negative for expired tasks.
Okay, so, I have a list table with 2 columns: codes and dates.
I want to display the LATEST 25 AND tell the user how long ago they were submitted.
So, for example:
ABCDEF (1 Second Ago)
CCDEE (12 Seconds Ago)
329492 (45 Minutes Ago)
I've gotten this far:
$result = mysql_query("SELECT `code` FROM `fc` ORDER by datetime LIMIT 25") or die(mysql_error());
but, it doesn't do what I want. It does the reverse. It shows what was inputted FIRST, not LAST.
My output looks like this:
$output .= "<li>" . htmlspecialchars($fetch_array["code"]) . "</li>";
I have NO Idea how to add the (time since) part.
Help?
Thanks :)
Consider ORDER BY datetime DESC to sort in the other direction.
Consider adding datetime to the SELECT list, so you can access the posting date in PHP. You can then use PHP date/time functions to calculte the difference between the current date, and the date posted, to work out how long ago the posting was posted.
Added: a bit of code to calculate the time since the posting in a friendly format.
$seconds = time() - strtotime($fetch_array["datetime"]);
if($seconds < 60)
$interval = "$seconds seconds";
else
if($seconds < 3600)
$interval = floor($seconds / 60) . " minutes";
else
if($seconds < 86400)
$interval = floor($seconds / 3600) . " hours";
else
$interval = floor($seconds / 86400) . " days";
// You can keep on going
At the end $interval contains a textual representation of the interval
Try using
order by datetime desc
Then in PHP grab the current time, subtract the time returned from the query, and then take a look at this SO question about relative time to display your time in the proper units.
If I understand right the question the problem is that you don't specify the order of sort.
If you want to obtain the latest posts you have to specify the descendant order.
$result = mysql_query("SELECT code FROM fc ORDER by datetime DESC LIMIT 25") or die(mysql_error());
To fix the ordering:
"SELECT `code`, `datetime` FROM `fc` ORDER by datetime DESC LIMIT 25"
To get time diff, something like this should work. Note that you should refactor this into better methods, remove the "magic number" etc. (It can also be extended to be more sophisticated):
function getTimeAgo ($dateTime) {
$timestamp = new DateTime($dateTime);
$currentTimestamp = new DateTime();
$diff = $currentTimestamp->getTimestamp() - $timestamp->getTimestamp();
if($diff < 0) {
throw new Exception (__METHOD__ . ':parameter $dateTime can not be
in the future!');
}
if($diff < 60) {
return "$diff seconds ago";
}
if($diff < 3600) {
return $diff/60 . " minutes ago";
}
if($diff < 86400) {
return $diff/3600 . " hours ago";
}
}
Changing datetime order:
Try DESC or ASC at the end of your ORDER BY. This should do the trick:
SELECT code
FROM fc
ORDER BY datetime DESC
LIMIT 25
Time since:
Write or find a PHP function that converts MySQL datetime format to 'real English'. Here's a quick basic example:
<?php
// your code goes here
$timeStr = "2009-08-01 15:43:34";
$time = Sec2Time( time() - strtotime($timeStr) );
print_r($time);
// this converts mysql datetime into english
// borrowed from http://ckorp.net/sec2time.php
function Sec2Time($time){
if(is_numeric($time)){
$value = array(
"years" => 0, "days" => 0, "hours" => 0,
"minutes" => 0, "seconds" => 0,
);
if($time >= 31556926){
$value["years"] = floor($time/31556926);
$time = ($time%31556926);
}
if($time >= 86400){
$value["days"] = floor($time/86400);
$time = ($time%86400);
}
if($time >= 3600){
$value["hours"] = floor($time/3600);
$time = ($time%3600);
}
if($time >= 60){
$value["minutes"] = floor($time/60);
$time = ($time%60);
}
$value["seconds"] = floor($time);
return (array) $value;
}else{
return (bool) FALSE;
}
}
?>
And the output is:
Array ( [years] => 0 [days] => 4 [hours] => 5 [minutes] => 29 [seconds] => 38 )
Hope that helps