Horje

Tips (Total 2)


# Tips-1) How to convert a timestamp to Minute Ago in PHP

Here I bring a simple solution.

Time AGo PHP Function And Full Solution

Just copy following code and try in PHP File
index.php
Example: PHP
<?php
// 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' => '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';
}
?>
<?php
// Time
$date = '2023-08-19 07:11:31';
// Ago Code Final
echo time_elapsed_string($date);
?>

Output should be:

Time AGo PHP Function And Full Solution

# Tips-2) How to create PHP Date formatting

DateTime::createFromFormat -- date_create_from_format — Parses a time string according to a specified format

Example of PHP Date formatting

Here is the right way to use PHP Date formatting
index.php
Example: PHP
<?php
$date = DateTime::createFromFormat('j-M-Y', '02-Jan-2024');
echo $date->format('Y-m-d');
?>

Output should be:

Example of PHP Date formatting