how to get the date time or mintutes with past ago - php

How do I to get the minutes from a this datatime field
$time = strtotime('2010-04-28 17:25:43');
echo 'event happened '.humanTiming($time).' ago';
function humanTiming ($time)
{
$time = time() - $time; // to get the time since that moment
$time = ($time<1)? 1 : $time;
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}

With DateTime you can achieve it like this:
$d1 = new DateTime('2010-04-28 17:25:43'); // start time
$d2 = new DateTime(); // end time (now)
$diff_seconds = $d2->getTimestamp() - $d1->getTimestamp();
$diff_minutes = $diff_seconds/60; // get amount of minutes
echo round($diff_minutes);

Convert both to timestamps, subtract, and format again such as
$timestamp = strtotime('22-09-2008');
$since = time() - $timestamp;
echo date('Y-m-d H:i:s', strtotime($since));
Not tested, please check the date function documentation and this answer:
How to calculate the difference between two dates using PHP?

Related

How can I limit time ago function to under 12 months and post actual date for year or later?

I would like to post the actual date of an article (i.e. April 5, 2015) if it has been a year or more since its post. If less than a year, I would like to use the time ago function (i.e. 6 months ago).
I've tried commenting out the year in the HumanTiming Time Ago Function (posted by arnorhs) and adding an if/else condition to it
$time = strtotime('2015-04-05 17:25:43');
echo 'event happened '.humanTiming($time).' ago';
function humanTiming ($time)
{
$time = time() - $time; // to get the time since that moment
$time = ($time<1)? 1 : $time;
$tokens = array (
//31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
if($time > $tokens){
echo "April 5, 2015";
} else {
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
}
I expect the output to be "April 5, 2015", but it ignores the if/else condition and posts the date as "36 months ago".
How can I achieve the result I'm looking for?
using DateTime is way simpler
$now = new DateTime();
$then = new DateTime('April 5, 2015');
$diff = $now->diff($then); // returns DateInterval object or false on failure
if ($diff->y >= 1) {
// show your date
echo $then->format('Y-m-d H:i:s');
} else {
// show the interval
echo $diff->format('%d days ago');
}
check the documentation for more info
https://www.php.net/manual/en/class.dateinterval.php
https://www.php.net/manual/en/dateinterval.format.php
You need to check against the time of one year ago - not against the array $tokens. You can get the time of one year ago from strtotime('1 year ago'). If that is lesser than time()-$time (the current timestamp minus the $time timestamp), then the input-time is more than one year ago.
function humanTiming ($time) {
$time = time() - $time; // to get the time since that moment
$time = ($time<1)? 1 : $time;
$tokens = array (
//31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
if (time()-$time < strtotime("1 year ago")) {
return date("F jS, Y", time()-$time);
} else {
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'').' ago';
}
}
}
echo 'event happened '.humanTiming($time).'';
Live demo at https://3v4l.org/UH9df
<?php
$time = strtotime('2014-01-01 17:25:43');
function humanTiming ($time)
{
$back_time = $time;
$time = time() - $time; // to get the time since that moment
$time = ($time<1)? 1 : $time;
$tokens = array (
//31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < 31536000){
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
return date("Y-m-d H:i:s", $back_time);
}
echo 'event happened '.humanTiming($time);
?>
Everyone's different. I personally like to convert dates into unix timestamps (actual whole numbers) and work from there. Between the function and the function call are some display lines (echos) I added to give you a visual of what's happening. You can remove them, obviously.
<?php
//first here's the function
function date_less_year($entered_date_unix)
{
$difference = time() - $entered_date_unix;
//31536000 is a 'unix year'
if ($difference <= 31536000)
{
return true; //is less than or equal to a year
}
else if ($difference > 31536000)
{
return false; //is more than a year
}
}
/* display in the format you asked for. you can google 'php date' to learn of
* different formats you can use
*/
$entered_date_string = '2015-04-05 17:25:43';
$entered_date_to_display = date($entered_date_string);
echo $entered_date_to_display . ' is the date entered<br/>';
//let's turn to a unix timestampe to compare differences
$entered_date_unix = strtotime($entered_date_string);
echo $entered_date_unix . ' is the unix timestamp for entered date<br/>';
echo time() . ' is unix time for NOW <br/>';
if (date_less_year($entered_date_unix) == true)
{
//do something for less than a year
echo 'is less than a year!';
}
else
{
//do something for more than a year
echo 'is more than a year!';
}
?>

Change elapsed time after a month to different format

I am using codeigniter and I have this code below It converts date in to a elapsed time to something like Asked 1 month, 3 weeks ago
If the date is older than a month I would like it to only display like date Asked Sept 01 05:34:13 and if older than a year Asked Sept 01 2015 05:34:13
Currently if time is under month prints out like below which is fine
example Asked 1 minute, 14 seconds ago
example Asked 2 weeks, 3 hours ago
$this->when_was_question_posted(strtotime('2016-09-01 05:34:13'))
Question how can I make sure that if the date is older than a month
then display like date Asked Sept 01 05:34:13 and if older than a
year Asked Sept 01 2015 05:34:13
function when_was_question_posted($distant_timestamp, $max_units = 2) {
$i = 0;
$time = time() - $distant_timestamp; // to get the time since that moment
$tokens = [
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
];
$responses = [];
while ($i < $max_units) {
foreach ($tokens as $unit => $text) {
if ($time < $unit) {
continue;
}
$i++;
$numberOfUnits = floor($time / $unit);
$responses[] = $numberOfUnits . ' ' . $text . (($numberOfUnits > 1) ? 's' : '');
$time -= ($unit * $numberOfUnits);
break;
}
}
if (!empty($responses)) {
return 'Asked ' . implode(', ', $responses) . ' ago';
}
return 'Just now';
}
Here is something to get you going...
$date_now = new DateTime();
$date = new DateTime('2014-04-01 00:00:00');
$interval = $date_now->diff($date);
if($interval->y > 0) {
echo "More than a year";
echo "<br>";
$display_date = $date->format('M d Y h:i:s');
} elseif($interval->m > 0) {
echo "More than a month";
echo "<br>";
$display_date = $date->format('M d h:i:s');
} else {
// Call your existing function
}

Confused about date-time difference in months and years

I've made a function to calculate the age between two date-times, but I had a problem with the months and the years, because the months could be 29, 30, or 31 days.
I am confused, is this going to cause any problem? and if yes, then could someone suggest a solution please.
HERE IS MY FUNCTION
function time_age($date_time1,$date_time2 = ''){
//store current date-time if it hasn't been given
if (empty($date_time2)){
$date_time2 = date('Y-m-d H:i:s');
}
//get date-time difference in seconds
$time_age = strtotime($date_time2) - strtotime($date_time1);
//to store if seconds, minutes, hours, days, weeks, months, years
$time_age_type = 'seconds';
if ($time_age >= 60 and $time_age < 3600){
$time_age_type = 'minutes';
$time_age = number_format($time_age / 60, 0);
}elseif ($time_age >= 3600 and $time_age < 86400){
$time_age_type = 'hours';
$time_age = number_format($time_age / 3600, 0);
}elseif ($time_age >= 86400 and $time_age < 604800){
$time_age_type = 'days';
$time_age = number_format($time_age / 86400, 0);
}elseif ($time_age >= 604800 and $time_age < 2629743){
$time_age_type = 'weeks';
$time_age = number_format($time_age / 604800, 0);
}elseif ($time_age >= 2629743 and $time_age < 31556926){
$time_age_type = 'months';
$time_age = number_format($time_age / 2629743, 0);
}elseif ($time_age >= 31556926){
$time_age_type = 'years';
$time_age = number_format($time_age / 31556926, 0);
}
return $time_age.' '.$time_age_type.' ago';
}
I will suggest this alternative solution so I took this example from https://php.net :
<?php
$val1 = '2014-03-18 10:34:09.939';
$val2 = 'now';
$datetime1 = new DateTime($val1);
$datetime2 = new DateTime($val2);
echo "<pre>";
var_dump($datetime1->diff($datetime2));
https://secure.php.net/manual/en/datetime.diff.php#114656
How about this function which is what I use?
/**
* Get a string of length of time elapsed since a specified time.
*
* #param int $time the specified time to check
* #return string returns a string stating the length of time ago.
*/
function timeSince($time)
{
$timeDifference = time() - $time;
$timeTokens = [
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'min',
1 => 'sec'
];
foreach ($timeTokens as $unit => $text) {
if ($timeDifference < $unit) continue;
$noUnits = floor($timeDifference / $unit);
return $noUnits . " " . $text . (($noUnits > 1) ? "s ago" : " ago");
}
}
Usage
echo timeSince(time() - 86400);
Output
1 day ago
You can also use the DateTime class' diff function:
An OO approach:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
A Procedural approach:
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
Note: If you are using the DateTime class and wish to find the difference between two UNIX timestamps then you have to put an # sign before the timestamp, for example:
new DateTime("#" . $yourUnixTimestamp);
Otherwise it will throw an error.

PHP converting DATETIME into time ago function, seconds, minutes, hours, days etc [duplicate]

This question already has answers here:
Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...
(32 answers)
Closed 8 years ago.
I am using the following php function to convert my standard DATETIME result into a facebook style time ago, which shows the number of seconds, minutes and hours, days etc of that date.
Here's my php function:
<?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"; }
return "a few seconds ago";
}
?>
And here's where I call the function:
echo pretty_relative_time($row1['date']);
the problem I'm having is the script almost works 100%, however if something is dated within an hour it only ever shows 'about an hour ago' even if I've posted something within a couple of minutes or seconds. Can someone please show me what I am doing wrong? My date is stored as a DATETIME stamp
You can use this function its working 100% correct. . .
function Myfunction ($time)
{
$time = time() - $time; // to get the time since that moment
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
And call in this way. .
$time = strtotime($time);
$time = Myfunction($time);

php date formatting for time difference

I just want to output as a result of a script to be executed through CLI the time the execution of the script took.
for doing that, I set a var at the start of the script
$start_time = time();
and then at the end
date('H:i:s',time() - $start_time);
the problem is that even when the ellapsed time might be in the range of seconds or minutes, it always print that at least an hour has passed:
>>> echo date('H:i:s',1);
01:00:01
>>> echo date('H:i:s', 10);
01:00:10
>>> echo date('H:i:s',3599);
01:59:59
>>> echo date('H:i:s',3600);
02:00:00
shouldn't it display 00:XX:YY, when less than an hour has passed?
is there something I'm missing, is there a bug?
thanks for your help!
Don't use date(). When you have time() - $start_time the result is in seconds. Multiply this up if you want it in mintues etc. or use the following function to convert the seconds to Hours, Minutes and Seconds.
<?php /**
*
* #convert seconds to hours minutes and seconds
*
* #param int $seconds The number of seconds
*
* #return string
*
*/
function secondsToWords($seconds) {
/*** return value ***/
$ret = "";
/*** get the hours ***/
$hours = intval(intval($seconds) / 3600);
if($hours > 0)
{
$ret .= "$hours hours ";
}
/*** get the minutes ***/
$minutes = bcmod((intval($seconds) / 60),60);
if($hours > 0 || $minutes > 0)
{
$ret .= "$minutes minutes ";
}
/*** get the seconds ***/
$seconds = bcmod(intval($seconds),60);
$ret .= "$seconds seconds";
return $ret;
} ?>
Example usage:
<?php
/*** time since EPOCH ***/
echo secondsToWords(time());
?>
You could try this function:
<?
$time = strtotime('2010-04-28 17:25:43');
echo 'event happened '.humanTiming($time).' ago';
function humanTiming ($time)
{
$time = time() - $time; // to get the time since that moment
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
?>
From here:
PHP How to find the time elapsed since a date time?
This will give you a better means of getting the difference. Simply replace strtotime('2010-04-28 17:25:43'); with whatever your start date/time is (as a timestamp). One of the benefits is the function can be repurposed elsewhere.
Try this:
echo "Time left:". date('H:i:s', (strtotime('2000-01-01 00:00:00') + (time()-$start_time) ));
Use gmdate() instead of date() to display the correct time difference and compensate for the server's time zone
This function gives a "fully" formatted human readable time string..
function humantime ($oldtime, $newtime = null, $returnarray = false) {
if(!$newtime) $newtime = time();
$time = $newtime - $oldtime; // to get the time since that moment
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
$htarray = array();
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
$htarray[$text] = $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
$time = $time - ( $unit * $numberOfUnits );
}
if($returnarray) return $htarray;
return implode(' ', $htarray);
}

Categories