A Selection of really useful Date & Time PHP Snippets. Which are available to use under the MIT license.

Calculates the average time it would take to read a body of text depending on words per minutes, ex. “Less than a minute.”, “3 hours 14 minutes.”, “15 minutes.”

<?php
/* 
 * -------------------------------------------------------
 * readTime
 * -------------------------------------------------------
 * @Version: 1.0.0
 * @Author:  FireDart
 * @Link:    http://www.firedartstudios.com/
 * @GitHub:  https://github.com/FireDart/snippets/DateTime
 * @License: The MIT License (MIT)
 * 
 * Calculates the average time it would take to read a 
 * body of text depending on words per minutes, ex.
 * 
 * "Less than a minute."
 * "3 hours 14 minutes."
 * "15 minutes."
 * 
 * -------------------------------------------------------
 * Requirements
 * -------------------------------------------------------
 * PHP 5.3.0+
 * 
 * -------------------------------------------------------
 * Suggestion on WPM (Words Per Minute)
 * -------------------------------------------------------
 * The default words per minute is 300, this is the average 
 * of an adult. Need to target a specific level?
 * 
 * 3rd Grade              = 150wpm
 * 8th Grade              = 250wpm
 * Average Adult          = 300wpm
 * College Student        = 450wpm
 * High Level Executive   = 575wpm
 * College Professor      = 675wpm
 * Speed Readers          = 1,500wpm
 * Speed Reading Champion = 4,700wpm (Don't even try)
 * 
 * -------------------------------------------------------
 * Usage
 * -------------------------------------------------------
 * Basic (using 300/m)
 * echo readTime("The entire text");
 * 
 * All options
 * echo readTime("The entire text", 450);
 * 
 */
/* 
 * readTime
 * 
 * Calculates the average time it would take to read a 
 * body of text depending on words per minutes.
 * 
 * @param  mixed $text  The text you want to scan
 * @param  int   $speed Words per minutes, 300 average adult
 * @return str
 */
function readTime($text = null, $speed = 300) {
    try {
        // Check if any text exists to scan
        if(empty($text)) {
            throw new Exception('No content to analyze.');
        }
        // Make sure speed is no 0
        if($speed == 0) {
            throw new Exception('Words per minute can not be 0.');
        }
        // Trip extra space
        $length = trim($text);
        // Remove html from text
        $length = strip_tags($length);
        // Explode each space to count words
        $length = explode(" ", $length);
        // Count amount of words
        $length = count($length);
        // Get amount of words divided by words per minute
        $time   = round($length / $speed);
        // Is the words per minute 0? Less then a minute read then
        if($time == 0) {
            return "Less than a minute.";
        } else {
            // Calculate hours and minutes for text
            $hours = floor($time / 60);
            $minutes = $time - $hours * 60;
            $readTime = '';
            // Check how many hours it would take to read
            if($hours > 0) {
                $readTime .= $hours . " hour";
                // Do we need to add an s?
                if($hours > 1) {
                    $readTime .= "s";
                }
                // If minutes is not 0 add space
                if($minutes != 0) {
                    $readTime .= " and ";
                }
            }
            if($minutes > 0) {
                $readTime .= $minutes . " minute";
                // Do we need to add an s?
                if($minutes > 1) {
                    $readTime .= "s";
                }
            }
            // Return string, ex.
            // "3 hours 14 minutes." or "15 minutes."
            return $readTime . ".";
        }
    // Catch all errors and report back
    } catch(Exception $e) {
        return $e->getMessage();
    }
}

Take a Date, Time or DateTime and turns it into a human friendly time ago format, ex. “Just now.” (time < 30 seconds), “1 minute ago.”, “23 hours ago.”, “3 months ago.”

<?php
/* 
 * -------------------------------------------------------
 * timeAgo
 * -------------------------------------------------------
 * @Version: 1.0.0
 * @Author:  FireDart
 * @Link:    http://firedartstudios.com/
 * @GitHub:  https://github.com/FireDart/snippets/PHP/DateTime
 * @License: The MIT License (MIT)
 * 
 * Take a Date, Time or DateTime and turns it into a human 
 * friendly time ago format, ex.
 * 
 * "Just now." (time < 30 seconds)
 * "1 minute ago."
 * "23 hours ago."
 * "3 months ago."
 * 
 * timeAgo can also handel future dates but is not recommended
 * "In 30 seconds."
 * "In 5 months."
 * "In 2 years."
 * 
 * -------------------------------------------------------
 * Requirements
 * -------------------------------------------------------
 * PHP 5.3.0+
 * 
 * -------------------------------------------------------
 * Usage
 * -------------------------------------------------------
 * Basic
 * echo timeAgo('2014-07-27 20:00:00');
 * 
 * All options
 * echo timeAgo('2014-07-27 20:00:00', "America/New_York", false);
 * 
 */
/* 
 * timeAgo
 * 
 * Take a Date, Time or DateTime and turns it into a human 
 * friendly time ago format, ex.
 * 
 * @param mixed   $date     The date of "time ago"
 * @param str     $timezone The timezone you are the user is in
 * @param boolean $friendly Do we allow "Just now" & "In a moment"
 * @return str
 */
function timeAgo($date, $timezone = null, $friendly = true) {
    // Use try/catch loop for DateTime
    try {
        // If you need to set your default_timezone, list of zones:
        // http://php.net/manual/en/timezones.php
        if($timezone != null) {
            // Check if timezone is valid
            if(!in_array($timezone, timezone_identifiers_list())) {
                throw new Exception('Please input a valid timezone.');
            }
            date_default_timezone_set($timezone);
        }
        // Get the current moment in time
        $now      = new DateTime();
        // Get the time we will be working with & validate
        $ago      = new DateTime($date);
        // How much time is in-between them?
        $interval = $now->diff($ago);
        // Get intervals of each units
        $year     = $interval->format('%y');
        $month    = $interval->format('%m');
        $day      = $interval->format('%d');
        $hour     = $interval->format('%h');
        $minute   = $interval->format('%i');
        $second   = $interval->format('%s');
        // Check if it is a date in the future
        if($interval->invert == 0) {
            // If it is we might as well handel it
            if($interval->format('%y') == "00000") {
                $time = $year;
                $unit = "year";
            } elseif($interval->format('%m%y') == "0000"){
                $time = $month;
                $unit = "month";
            } elseif($interval->format('%d%m%y') == "000"){
                $time = $day;
                $unit = "day";
            } elseif($interval->format('%h%d%m%y') == "00"){
                $time = $hour;
                $unit = "hour";
            } elseif($interval->format('%i%h%d%m%y') == "0"){
                $time = $minute;
                $unit = "minute";
            } else{
                $time = $second;
                $unit = "second";
            }
        }
        // Check what unit we should use
        if($interval->format('%i%h%d%m%y') == "00000") {
            $time = $second;
            $unit = "second";
        } elseif($interval->format('%h%d%m%y') == "0000"){
            $time = $minute;
            $unit = "minute";
        } elseif($interval->format('%d%m%y') == "000"){
            $time = $hour;
            $unit = "hour";
        } elseif($interval->format('%m%y') == "00"){
            $time = $day;
            $unit = "day";
        } elseif($interval->format('%y') == "0"){
            $time = $month;
            $unit = "month";
        } else{
            $time = $year;
            $unit = "year";
        }
        // Make it more personable
        if($unit == "second" && $time < 30 && $interval->invert != 0 && $friendly === true) {
            return "Just now.";
        }
        if($unit == "second" && $time < 30 && $interval->invert == 0 && $friendly === true) {
            return "In a moment.";
        }
        // Add s if number is greater then 1
        if($time > 1) {
            $unit .= "s";
        }
        // Return sentence
        if($interval->invert == 0) {
            return "In {$time} {$unit}.";
        } else {
            return "{$time} {$unit} ago.";
        }
    // Catch all errors and report back
    } catch(Exception $e) {
        echo $e->getMessage();
    }
}

The function getDateTimeFormat create a valid MySQL-Datetime-Formatted datetime.

By default the function will create the current datetime. You can pass a DateTime Instance to change the output.

Usage

function getDateTimeFormat(DateTime $dateTime = null): string
{
return ($dateTime ?? new DateTime('now'))->format('Y-m-d H:i:s');
}

echo \basteyy\VariousPhpSnippets\getDateTimeFormat(); 
// Result: current date time in format: yyy-dd-mm hh:mm:ii 

echo \basteyy\VariousPhpSnippets\getDateTimeFormat((new DateTime('2020-01-01 10:10:10'))->modify('+2 years')); 
// Result: 2022-01-01 10:10:10

The function getNiceDateTimeFormat returns a nice to read version of a given or, if first argument is null, the current MySQL-Datetime-Formatted datetime.

By default, the function will create the current datetime. You can pass a DateTime Instance to change the output.

Be default, the function used the current default Locale. You can set up a Locale somewhere in your code (before calling the function) or pass a locale as a string as the second parameter to the function.

Usage

function getNiceDateTimeFormat(DateTime $dateTime = null, string $locale = null): string
 {
     if (!$dateTime) {
        $dateTime = new \DateTime('now');
      }
     if (!isset($locale)) {
        $locale = substr(\Locale::getDefault(), 0, 2);
     }
     return $dateTime->format(match ($locale) {
         'de' => 'd. F y, H:i',
         default => 'F d. y, h:i a'
     });
}

echo \basteyy\VariousPhpSnippets\getNiceDateTimeFormat(); 
// Result: current date time in format: May 01 22, 09:59 pm 

echo \basteyy\VariousPhpSnippets\getDateTimeFormat((new DateTime('2020-01-01 10:10'))->modify('+2 years'), 'de'); 
// Result: 01. Januar 2022, 10:10 echo \basteyy\VariousPhpSnippets\getDateTimeFormat((new DateTime('2020-01-01 10:10'))->modify('+2 years')); 

// Result: January 01 22, 10:10 am

Both Snippets above MIT licensed.