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.
My Answer:
You can solve the issue by setting the default timezone in your PHP script. You can set the timezone to 'Europe/Istanbul' for Turkish time. Here's how you can modify your code:
php
function time_elapsed_string($datetime, $full = false) {
date_default_timezone_set('Europe/Istanbul'); // Set the default timezone to Turkish time
$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';
}
$dateok = "2022-05-15 09:22:16"; // year-month-date hours:minute:second
echo time_elapsed_string($dateok);
By setting the default timezone to 'Europe/Istanbul', the DateTime object will use the Turkish time for calculations, and you should get the correct output for your examples.
Rate this post
3 of 5 based on 5788 votesComments