How to separate elapsed time in three parts? - php

In $periods array first column is for single day (1 godinu), second is for more then one (2 godine) and third is the same but after 4 days in my country, we say different (5 godina).
And it is different for everything, here is an example for all of them:
year = (1 = godinu), (2,3,4 = godine), (after 4 = godina)
month = (1 = mesec), (2,3,4 = meseca), (after 4 = meseci)
week = (1 = nedelju), (2,3,4 = nedelje), (after 4 = nedelja)
day = (1 = dan), (after 1 = dana)
hour = (1 = sat), (2,3,4 = sata), (after 4 = sati)
minute = (1 = minut), (after 1 = minuta)
second = (1 = sekund), (2,3,4 = sekunde), (after 4 = sekundi)
<?php
function time_elapsed_string($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$periods = array(
'y' => ['godinu', 'godine', 'godina'],
'm' => ['mesec', 'meseca', 'meseci'],
'w' => ['nedelju', 'nedelje', 'nedelja'],
'd' => ['dan', 'dana', 'dana'],
'h' => ['sat', 'sata', 'sati'],
'i' => ['minut', 'minuta', 'minuta'],
's' => ['sekund', 'sekunde', 'sekundi']
);
$parts = array();
foreach ($periods as $k => &$v) {
if ($diff->$k) {
$parts[] = $diff->$k . ' ' . $v[$diff->$k > 1];
}
}
if (!$full) $parts = array_slice($parts, 0, 1);
return $parts ? 'pre ' . implode(', ', $parts) : DATE_NOW;
}
?>

The correct units for each value can easily be chosen using a simple switch statement.
function time_elapsed_string($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$periods = array(
'y' => ['godinu', 'godine', 'godina'],
'm' => ['mesec', 'meseca', 'meseci'],
'w' => ['nedelju', 'nedelje', 'nedelja'],
'd' => ['dan', 'dana', 'dana'],
'h' => ['sat', 'sata', 'sati'],
'i' => ['minut', 'minuta', 'minuta'],
's' => ['sekund', 'sekunde', 'sekundi']
);
$parts = array();
foreach ($periods as $k => $v) {
if ($diff->$k) {
switch ($diff->$k) {
case 1:
$unit = $v[0];
break;
case 2:
case 3:
case 4:
$unit = $v[1];
break;
default:
$unit = $v[2];
}
$parts[] = $diff->$k . ' ' . $unit;
}
}
if (!$full) $parts = array_slice($parts, 0, 1);
return $parts ? 'pre ' . implode(', ', $parts) : DATE_NOW;
}
echo time_elapsed_string('last month -8days -3hours', true);
// pre 1 mesec, 1 nedelju, 1 dan, 2 sata, 59 minuta, 59 sekundi

Related

PHP Datetime Function date convert

I have a problem. How can i solve this problem.
My Function
function time_elapsed_string($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'mounth',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'sencond',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? '' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just time';
}
$dateok="2022-05-15 09:22:16"; // year-mounth-date hours:minute:second
echo time_elapsed_string($dateok);
I want convert data turkish time but my function calculating wrong .
(I Think is $now = new DateTime; my date format does not match maybe We Have GMT+3 Turkish Time ... I Dont know)
Note : $dateok has a variable value.
EXAMPLE 1 :
Suppose now is (current time ) 2022-05-15 10:47:00
Suppose my date is namely $dateok = 2022-05-15 10:46:00
output // 2 hour ago -> this is false -> must be : 1 minute ago
EXAMPLE 2 :
Suppose now is (current time ) 2022-05-15 10:47:00
Suppose my date is namely $dateok = 2022-05-14 10:47:00
output // 21 hour ago -> this is false -> must be : 1 day ago
SOLUTION : add date_default_timezone_set('') and problem solved.

how do i use mentioned issue in PHP timedate ago

so hello i am trying to use this most used php script linked here
Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...
but i cannot get it working, i thought i would fill variable with $datetime with the date i want to differente with
i am inputting date with this format "1614084957" but yet i get error
Error: Uncaught Error: Class 'datetime' not found in
i dont know what wrong its included the function is above the desired echo
function time_elapsed_string($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}
if ($page->id == 1) {
$kat = $pages->get('/kategorie/');
include('chunks/hry.php');
}
in hry.php i jsut have som foreach and ifs
i have foreach for each a link to game a i wanted to use this function to determine when this game was created,
Add \ before your class name
$now = new \DateTime;
$ago = new \DateTime($datetime);

How to find the time elapsed since a date time and what time is it like notification facebook? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
My code is like this :
<?php
function time_elapsed_string($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}
$created_date = '2016-06-28 23:30:00';
echo time_elapsed_string($created_date);
?>
I want to make like datetime in notification facebook
It is like this :
June 26 at 11:45
yesterday at 7:00
12 minutes ago
I want to make like that
Any solution to solve my problem?
I have updated your function. Please add required validation
function time_elapsed_string($datetime, $full = false) {
$now = new DateTime();
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k ;//. ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
if(!empty($string['y']) || !empty($string['m']) || !empty($string['w']) )
{
echo showdate($datetime,'w')."<br>";
}
elseif(!empty($string['d']) )
{
if($string['d'] > 1)
{
echo showdate($datetime,'w')."<br>";
}
else
{
echo showdate($datetime,'d')."<br>";
}
}
elseif(!empty($string['h']) )
{
echo implode(', ', $string) . 'h ago';//"<br>";
}
elseif(!empty($string['i']) )
{
echo implode(', ', $string) . 'mints ago';//"<br>";
}
elseif( !empty($string['s']))
{
echo 'just now';//"<br>";
}
// return $string ? implode(', ', $string) . ' ago' : 'just now';
}
function showdate($dt,$type)
{
$mydt = new DateTime($dt);
if($type == 'd')
{
$str = 'Yesterday at '.$mydt->format('H:i:s ');
}
elseif($type == 'h')
{
//$str = 'Yesterday at '.$mydt->format('H:i:s ');
}
else
{
$str = $mydt->format('M d');
$str .= ' at '.$mydt->format('H:i:s ');
}
return $str;
}
$created_date = '2016-06-29 04:50:00';
echo time_elapsed_string($created_date);

How to view how old something is

Say I have some posts and they all have the time they were submitted.
Now what I want to do is check how long ago they were posted in minutes. For example post 1 was posted 40 minutes ago and post 2 was posted 479 minutes ago and so on…
And of course I would run that $data array in a loop but for the time being its understandable. And also the time includes a timestamp so instead of just the time it includes the date and time.
php:
$data = ["POST1"=>"3:10PM","POST2"=>"3:40PM","POST3"=>"4:20PM","POST4"=>"5:15PM"]
html:
<div>
<p><?php echo $data[0] ?><p>
</div>
Here is what would help you:
<?php
function time_elapsed_string($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}
$date = date_parse_from_format('Y-d-m H:i:s', '2014-02-05 5:22:35');
$unixTimestamp = mktime(
$date['hour'], $date['minute'], $date['second'],
$date['month'], $date['day'], $date['year']
);
echo time_elapsed_string(date('Y-m-d H:i:s',$unixTimestamp), false);
and here is a working fiddle for you.

Calculate number of days,hours,minutes,seconds only working hours

I have a php function to calculate timestamp (start date) to current (end) date that will return 1hr 30min 2s format. What I want to achieve is to calculate only from 8AM to 5PM of a working day. Anything that goes beyond will not be counted. Here is the php code I have.
class duration_computation {
function duration( $time ) {
$d[0] = array(1, "s");
$d[1] = array(60, "min");
$d[2] = array(3600, "hr");
$d[3] = array(86400, "dy");
$d[4] = array(604800, "wk");
$d[5] = array(2592000, "mth");
$d[6] = array(31104000, "yr");
$numbers = array();
$result = "";
$now = time();
$time_difference = ( $now - $time );
$seconds_left = $time_difference;
for ( $i = 6; $i > -1; $i-- ) {
$numbers[$i] = intval( $seconds_left / $d[$i][0] );
$seconds_left -= ( $numbers[$i] * $d[$i][0] );
if ( $numbers[$i] != 0 ) {
$result.= abs($numbers[$i]) . "" . $d[$i][1] . (($numbers[$i]>1)?'':'') ." ";
}
}
return $result;
}
}
$duration = new duration_computation();
echo $duration->duration($trail->duration);
Forget about date(), strtotime(), time(), etc. function, use DateTime :
Use example :
$from = '2013-09-06 15:45:32';
$to = '2013-09-14 21:00:00';
echo some_func_name($from, $to);
Output :
1 day, 22 hours, 14 minutes, 28 seconds
Function :
function some_func_name($from, $to) {
$workingDays = [1, 2, 3, 4, 5]; # date format = N
$workingHours = ['from' => ['08', '00'], 'to' => ['17', '00']];
$start = new DateTime($from);
$end = new DateTime($to);
$startP = clone $start;
$startP->setTime(0, 0, 0);
$endP = clone $end;
$endP->setTime(23, 59, 59);
$interval = new DateInterval('P1D');
$periods = new DatePeriod($startP, $interval, $endP);
$sum = [];
foreach ($periods as $i => $period) {
if (!in_array($period->format('N'), $workingDays)) continue;
$startT = clone $period;
$startT->setTime($workingHours['from'][0], $workingHours['from'][1]);
if (!$i && $start->diff($startT)->invert) $startT = $start;
$endT = clone $period;
$endT->setTime($workingHours['to'][0], $workingHours['to'][1]);
if (!$end->diff($endT)->invert) $endT = $end;
#echo $startT->format('Y-m-d H:i') . ' - ' . $endT->format('Y-m-d H:i') . "\n"; # debug
$diff = $startT->diff($endT);
if ($diff->invert) continue;
foreach ($diff as $k => $v) {
if (!isset($sum[$k])) $sum[$k] = 0;
$sum[$k] += $v;
}
}
if (!$sum) return 'ccc, no time on job?';
$spec = "P{$sum['y']}Y{$sum['m']}M{$sum['d']}DT{$sum['h']}H{$sum['i']}M{$sum['s']}S";
$interval = new DateInterval($spec);
$startS = new DateTime;
$endS = clone $startS;
$endS->sub($interval);
$diff = $endS->diff($startS);
$labels = [
'y' => 'year',
'm' => 'month',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
];
$return = [];
foreach ($labels as $k => $v) {
if ($diff->$k) {
$return[] = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
}
}
return implode(', ', $return);
}
This function can be shorter/better; but that is your job now ;)

Categories