PHP Date Helpers

by Kiki Cuyler March 12, 2026 Public
61 views Raw Download Revisions (v1)
date-helpers.php php Raw
<?php
/**
 * Human-readable time diff (like "3 hours ago").
 */
function time_ago( int $timestamp ): string {
    $diff = time() - $timestamp;

    if ( $diff < 60 )        return 'just now';
    if ( $diff < 3600 )      return floor( $diff / 60 ) . ' min ago';
    if ( $diff < 86400 )     return floor( $diff / 3600 ) . ' hours ago';
    if ( $diff < 604800 )    return floor( $diff / 86400 ) . ' days ago';
    if ( $diff < 2592000 )   return floor( $diff / 604800 ) . ' weeks ago';
    if ( $diff < 31536000 )  return floor( $diff / 2592000 ) . ' months ago';

    return floor( $diff / 31536000 ) . ' years ago';
}

/**
 * Return array of dates between two timestamps.
 */
function date_range( string $start, string $end, string $format = 'Y-m-d' ): array {
    $dates  = [];
    $period = new DatePeriod(
        new DateTime( $start ),
        new DateInterval( 'P1D' ),
        ( new DateTime( $end ) )->modify( '+1 day' )
    );
    foreach ( $period as $date ) {
        $dates[] = $date->format( $format );
    }
    return $dates;
}
Skip to toolbar