date to time ago ? without useing strtime? - php

ok i have a date
date('Y-m-d H:i:s');
how can we make it like 0 seconds ago or x year x month x day x minutes x seconds ago ? but without useing the str_time ( php 5.3.3 )
edit*
i mean is some.date - time.now = someyear some month someday someminutes someseconds ago.
like facebook or stackoverflow ( updated. i mean like that. – Adam Ramadhan 2 mins ago edit )
edit*
some say to use sktime ?
the 2 mins ago.
Thanks
Adam Ramadhan

You should try out this (looks exactly like the krike answer but this one is fixed!)
<?php
function ago($timestamp){
$difference = time() - $timestamp;
$periods = array("second", "minute", "hour", "day", "week", "month", "years", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
for($j = 0; $difference >= $lengths[$j]; $j++)
$difference /= $lengths[$j];
$difference = round($difference);
if($difference != 1) $periods[$j].= "s";
$text = "$difference $periods[$j] ago";
return $text;
}
?>
Just do this---
echo ago($timeofthethingyouwant);
And remember this works with this type of format of time----
time(); //Or it looks like this 1299951275!
This works for sure and it is great and light weight script! For more head to this link--
http://drupal.org/node/61565
Hope it works!

Why not just subtract 30 from the output of time() ?
date('Y-m-d H:i:s',time()-30);
time() returns the current time measured in terms of number of seconds since epoch, so subtracting 30 from it gives the timestamp of the time 30 sec ago

function nicetime($fromDate, $toDate = NULL, $precision = -1, $separator = ', ', $divisors = NULL) {
if ( is_null( $toDate ) ) {
$toDate = $this->date_get('Asia/Jakarta');
}
// Determine the difference between the largest and smallest date
$dates = array(strtotime($fromDate), strtotime($toDate));
$difference = max($dates) - min($dates);
// Return the formatted interval
return $this->format_interval($difference, $precision, $separator, $divisors);
}
/**
* Formats any number of seconds into a readable string
*
* #param int Seconds to format
* #param string Seperator to use between divisors
* #param int Number of divisors to return, ie (3) gives '1 Year, 3 Days, 9 Hours' whereas (2) gives '1 Year, 3 Days'
* #param array Set of Name => Seconds pairs to use as divisors, ie array('Year' => 31536000)
* #return string Formatted interval
*/
function format_interval($seconds, $precision = -1, $separator = ', ', $divisors = NULL)
{
// Default set of divisors to use
if(!isset($divisors)) {
$divisors = Array(
'Year' => 31536000,
'Month' => 2628000,
'Day' => 86400,
'Hour' => 3600,
'Minute' => 60,
'Second' => 1);
}
arsort($divisors);
// Iterate over each divisor
foreach($divisors as $name => $divisor)
{
// If there is at least 1 of thie divisor's time period
if($value = floor($seconds / $divisor)) {
// Add the formatted value - divisor pair to the output array.
// Omits the plural for a singular value.
if($value == 1)
$out[] = "$value $name";
else
$out[] = "$value {$name}s";
// Stop looping if we've hit the precision limit
if(--$precision == 0)
break;
}
// Strip this divisor from the total seconds
$seconds %= $divisor;
}
// FIX
if (!isset($out)) {
$out[] = "0" . $name;
}
var_dump($out);
// Join the value - divisor pairs with $separator between each element
return implode($separator, $out);
}

I found the following function when searching on google, i tested the code out and it seems to work perfectly.
function ago($timestamp){
$difference = time() - $timestamp;
$periods = array("second", "minute", "hour", "day", "week", "month", "years", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
for($j = 0; $difference >= $lengths[$j]; $j++)
$difference /= $lengths[$j];
$difference = round($difference);
if($difference != 1) $periods[$j].= "s";
$text = "$difference $periods[$j] ago";
return $text;
}
you would then call it as
echo ago($time);

Fairly simply - you need start and current timestamps. For instance, to see the number of minutes passed from a start date of this evening (8/22/2010 9pm PST):
$start = strtotime('8/22/2010 9pm');
printf('%d minutes ago', (time() - $start) / 60);
// My Output: 36 minutes ago. Will vary, depending on the current time/zone.
The 60 divisor is to get minutes. For seconds there'd be no division. For hours, days, years, etc. use different divisors. The following solution has a sample function for formatting timestamps:
How to display "12 minutes ago" etc in a PHP webpage?

Related

Calculate Total time from array in php if total time greater than 24 hours

I want to get the sum of the time in array. There are a lot of questions asked before related this question. Only problem this solution work the only sum is less than 24 hours. After 24 hours it will start at 00:00:00. How do I get more than 24 hours as total?
<?php
$total = [
'00:02:55',
'00:07:56',
'01:03:32',
'15:13:34',
'02:13:44',
'03:08:53',
'13:13:54'
];
$sum = strtotime('00:00:00');
$sum2=0;
foreach ($total as $v){
$sum1=strtotime($v)-$sum;
$sum2 = $sum2+$sum1;
}
$sum3=$sum+$sum2;
echo date("H:i:s",$sum3);
?>
RESULT
11:04:28
Expected result
35:04:28
DEMO LINK
Try the following code
<?php
function explode_time($time) { //explode time and convert into seconds
$time = explode(':', $time);
$time = $time[0] * 3600 + $time[1] * 60;
return $time;
}
function second_to_hhmm($time) { //convert seconds to hh:mm
$hour = floor($time / 3600);
$minute = strval(floor(($time % 3600) / 60));
if ($minute == 0) {
$minute = "00";
} else {
$minute = $minute;
}
$time = $hour . ":" . $minute;
return $time;
}
$time = 0;
$time_arr = [
'00:02:55',
'00:07:56',
'01:03:32',
'15:13:34',
'02:13:44',
'03:08:53',
'13:13:54'
];
foreach ($time_arr as $time_val) {
$time +=explode_time($time_val); // this fucntion will convert all hh:mm to seconds
}
echo second_to_hhmm($time);
?>
With the external DateTime Extension dt you can add all times to a date.
With DateTime::diff you get the result:
$dt = dt::create("2000-1-1"); //fix Date
$dtsum = clone $dt;
foreach($total as $time){
$dtsum->addTime($time);
}
$diff = $dt->diff($dtsum);
printf('%d:%02d:%02d',$diff->days * 24 + $diff->h,$diff->i,$diff->s);
Output:
35:04:28
Update
Without a DateTime-Extension:
$dt = date_create("2000-1-1"); //fix Date
$dtsum = clone $dt;
foreach($total as $time){
$timeArr = explode(":",$time);
$secondsAdd = $timeArr[0] * 3600 + $timeArr[1] * 60 +$timeArr[2];
$dtsum->modify($secondsAdd." Seconds");
}
$diff = $dt->diff($dtsum);
printf('%d:%02d:%02d',$diff->days * 24 + $diff->h,$diff->i,$diff->s);
Look at what you are doing: using time to make computations ignoring date part.
Maybe considering things in another way : 1 hour = 60 seconds * 60 minutes. So convert all you iterations as seconds, do the sum at the end and write time you need yourself.
Or, or you will use some greater things from php documentation
<?php
$january = new DateTime('2010-01-01');
$february = new DateTime('2010-02-01');
$interval = $february->diff($january);
// %a will output the total number of days.
echo $interval->format('%a total days')."\n";
// While %d will only output the number of days not already covered by the
// month.
echo $interval->format('%m month, %d days');
Adapt to your needs, and I am sure it will work well.
Personally I would completely avoid touching any date functions because you're not working with dates. You could do something like:
// Input data
$data = [
'00:02:55',
'00:07:56',
'01:03:32',
'15:13:34',
'02:13:44',
'03:08:53',
'13:13:54'
];
// Total to hold the amount of seconds
$total = 0;
// Loop the data items
foreach($data as $item):
$temp = explode(":", $item); // Explode by the seperator :
$total+= (int) $temp[0] * 3600; // Convert the hours to seconds and add to our total
$total+= (int) $temp[1] * 60; // Convert the minutes to seconds and add to our total
$total+= (int) $temp[2]; // Add the seconds to our total
endforeach;
// Format the seconds back into HH:MM:SS
$formatted = sprintf('%02d:%02d:%02d', ($total / 3600),($total / 60 % 60), $total % 60);
echo $formatted; // Outputs 35:04:28
So we loop the items in the input array and explode the string by the : to get an array containing hours, minutes and seconds in indexes 0, 1, and 2.
We then convert each of those values to seconds and add to our total. Once we're done, we format back into HH:MM:SS format

Difference between durations

I am creating a timesheet whereby it shows expected and actual hours.
The durations are saved like the below
23:15 - 23 hours and 15 mins
25:45 - 25 hours and 45 mins
I need to work out the difference in hours and mins between the two (extra hours worked)
I have tried the below
$acutal=='23:15';
$expected=='25:45';
$start_time = new DateTime("1970-01-01 $acutal:00");
$time = $start_date->diff(new DateTime("1970-01-01 $expected:00"));
This does work, however when the hours are over 24:00 it throws an error (obviously because it's reading it as time)
Uncaught exception 'Exception' with message 'DateTime::__construct():
Failed to parse time string (1970-01-01 25:45:00)
Is there another way to do this?
You could check if the number of hours are greater than 24, and if so, add a day, and remove 24 hours.
$actual='23:15';
$expected='25:45';
$day = 1;
list($hrs, $min) = explode(':', $expected);
if ($hrs > 24) { $day += 1; $hrs -= 24; }
$start_time = new DateTime("1970-01-01 $actual:00");
$time = $start_time->diff(new DateTime("1970-01-$day $hrs:$min:00"));
echo $time->format('%hh %Im');
Output:
2h 30m
Please also note that == is used to compare, not to assign.
You can also change the if ($hrs > 24) by while(), if there is 48 hours or more.
edit
As pointed out by #CollinD, if the time exceed the number of days of the month, it will fail. Here is another solution:
$actual='23:15';
$expected='25:45';
list($hrs, $min) = explode(':', $actual);
$total1 = $min + $hrs * 60;
list($hrs, $min) = explode(':', $expected);
$diff = $min + $hrs * 60 - $total1;
$start_time = new DateTime();
$expected_time = new DateTime();
$expected_time->modify("+ $diff minutes");
$time = $start_time->diff($expected_time);
echo $time->format('%hh %Im');
You can do it manually by keeping track of the number of minutes worked - this will be exact and will also allow you to show negative differences.
<?php
// get the difference in H:mm between two H:mm
function diff_time($actual, $expected) {
$diff_mins = mins($actual) - mins($expected);
return format_mins($diff_mins);
}
// convert a HH:mm to number of minutes
function mins($t) {
$parts = explode(':', $t);
return $parts[0] * 60 + $parts[1];
}
// convert number of minutes into HH:mm
function format_mins($m) {
$mins = $m % 60;
$hours = ($m - $mins) / 60;
// format HH:mm
return $hours . ':' . sprintf('%02d', abs($mins));
}
var_dump(diff_time('23:15', '25:45'));
var_dump(diff_time('25:15', '23:45'));
This outputs:
string(5) "-2:30"
string(4) "1:30"
.. first, 2:30 less than expected, for the second 1:30 more than expected.
You can try using datetime functions but it seems a lot more straightforward to me to treat the times as string, use split or explode to get hours and minutes, convert to integers, get the difference in minutes and convert it back to hours and minutes (integer divide by 60 and remainder).
$t1=explode(':',$expected);
$t2=explode(':',$actual);
$d=60*($t1[0]-$t2[0])+t1[1]-t2[1];
$result=str_pad(floor($d/60),2,'0',STR_PAD_LEFT).':'.str_pad($d%60,2,'0',STR_PAD_LEFT);

Displaying Date In A User Formated Style with php

I've noticed that Facebook, Twitter, and lots of other sites are using a relative date and time string description for user posts and comments.
For example, "comment written about 3 months ago" instead of "comment written on September 20, 2012." I decided to do the same thing on my site. In my site I need to display 1 day ago, 2 days ago, 3 days ago,...... 1 week ago, 2 weeks ago, .... 1 months ago, 2 months ago, ...... 1 year ago, 2 years ago... etc.
Already I have got user registered date and need to check it with current date and time and need to diplay it with above style on my home page.
In my database, user registered date format is like this .. '2012-09-23 09:11:02'
can anybody help me to build this script in php... and it will greatly appriciated.
Thank you.
Try the following code,
function time_elapsed_since ($postedDateTime){
$time = time() - $postedDateTime; // 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':'');
}
}
Usage:
time_elapsed_since($postedDateTime).' ago'; // 2012-09-23 09:11:02 format
Try with this
function time_ago($time) {
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
$now = time();
$difference = $now - $time;
$tense = "ago";
for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
$difference /= $lengths[$j];
}
$difference = round($difference);
if($difference != 1) {
$periods[$j].= "s";
}
return "$difference $periods[$j] 'ago' ";
}
Im guessing they are using unixtime ie the number of seconds since 1970 (which is standard). I suggest that should also keep your dates in that format. If they are using unix time you can use the following date function in PHP to convert it to your format above:
<?php
date('Y-m-t H:i:s', $facebookTime);
Regards,
Kevin

Hide hours and mins if they are zero in the function provided

The function below outputs hours:0 whether the time is <1 hour or mins:0 when mins<1.
How can I show only the variables that are not zero?
Thank you.
function time_difference($endtime){
$hours =date("G",$endtime);
$mins =date("i",$endtime);
$secs =date("s",$endtime);
$diff="'hours': ".$hours.",'mins': ".$mins.",'sec': ".$secs;
return $diff;
}
$end_time =strtotime("+7 hours") - strtotime($entry->pubDate);
$difference = time_difference($end_time);
echo $difference;
Another possible approach:
function time_difference($endtime){
$times=array(
'hours' => date("G",$endtime),
'mins' => date("i",$endtime),
'secs' => date("s",$endtime),
);
//added a "just a moment ago" feature for you
if (intval($times['hours'], 10) == 0
&& intval($times['mins'], 10) == 0) {
return "just a moment ago";
}
$diff='';
foreach ($times as $k=>$v) {
$diff.=empty($diff) ? '' : ',';
$diff.=intval($v, 10) == 0 ? '' : "'$k':$v";
}
return $diff;
}
Use the ? operator.
$diff=($hours > 0) ? "'hours': ".$hours : "";
$diff=$diff.($minutes > 0) ? etc...
For larger time ranges, you'd better use maths instead of using date():
function time_difference($endtime){
// hours can get over 23 now, $endtime is in seconds
$hours = floor($endtime / 3600);
// modulo (%) already rounds down, not need to use floor()
$mins = $endtime / 60 % 60;
// the remainder of $endtime / 60 are seconds in a minute
$secs = $endtime % 60;
// this array holds the hour, minute and seconds if greater than 0
$diff = array();
if ($hours) $diff[] = "'hours': $hours";
if ($mins) $diff[] = "'mins': $mins";
if ($secs) $diff[] = "'sec': $secs";
// join the values with a comma
$diff = implode(',', $diff);
if (!$diff) { // hours, mins and secs are zero
$diff = "just a moment ago";
}
return $diff;
}
The below function would only return hours in the range 0 - 23. If the time exceeds a day, hours become zero:
function time_difference($endtime){
$hours = (int)date("G",$endtime);
$mins = (int)date("i",$endtime);
$secs = (int)date("s",$endtime);
// this array holds the hour, minute and seconds if greater than 0
$diff = array();
if ($hours) $diff[] = "'hours': $hours";
if ($mins) $diff[] = "'mins': $mins";
if ($secs) $diff[] = "'sec': $secs";
// join the values with a comma
$diff = implode(',', $diff);
if (!$diff) { // hours, mins and secs are zero
$diff = "just a moment ago";
}
return $diff;
}
(int) is needed to turn the string returned by date() into a string. "01" becomes 1 and "00" becomes "0" using this.

Convert dates to hours

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.

Categories