readableDate.js

a little javascript util to convert a Date object into a nice readable string like "3 hours ago" or "6 weeks ago", etc.

(well actually ive dug out a bit of my php code from an ancient project and rewritten it in js)

source: /js/readabledate.js

let testDate = new Date("Tue, 02 Jun 2026 12:50:23 GMT");

// returns ""
document.write(readableDate(testDate));

page last updated:

readableDate(new Date(document.lastModified));

time since 1st jan 26:

time since millennium:

my ancient php code:
<?php

function readableDate( $timestamp ) {

    $diff = time() - $timestamp;

    if( $diff < 60 * 60 ) {
        $period = floor( $diff / 60 );
        $unit = 'minute';
         if( $period < 1 ) {
             // never show a time of 0 minutes
             $period = 1;
         }
     } elseif( $diff < 60 * 60 * 24 ) {
        $period = floor( $diff / ( 60 * 60 ) );
         $unit = 'hour';
     } elseif( $diff < 60 * 60 * 24 * 14 ) { 
      // show "days" if time is within two weeks
      $period = floor( $diff / ( 60 * 60 * 24 ) );
         $unit = 'day';
     } else {
       $period = floor( $diff / ( 60 * 60 * 24 * 7 ) );
        $unit = 'week';
     }

     $textdate = $period . ' ' . 
        $unit . ( $period != 1 ? 's' : '' ) 
        . ' ago';
    return $textdate;
}
?>

new JavaScript version:
<script>

function readableDate(dateObj) 
{  
try
{
  let diff = (Date.now() - dateObj.getTime()) / 1000;
  let period = 0;
  let unit = "";
  
  const anHour = 60 * 60;
  const aDay = anHour * 24;
  const aWeek = aDay * 7;
  const aMonth = aDay * 30;
  const aYear = aDay * 365;
  
  if(diff < anHour) 
  {
    period = Math.floor(diff / 60);
    unit = 'minute';
    
    // never show a time of 0 minutes
    if(period < 1) 
    {
      period = 1;
    }
  } 
  else if(diff < aDay) 
  {
    period = Math.floor(diff / anHour);
    unit = 'hour';
  } 
  else if(diff < aWeek)
  { 
    period = Math.floor(diff / aDay);
    unit = 'day';
  } 
  else if(diff < aWeek * 2)
  { 
    period = Math.round(diff / aDay);
    unit = 'day';
  } 
  else if(diff < aMonth * 2) 
  {
    period = Math.round(diff / aWeek);
    unit = 'week';
  } 
  else if(diff < aYear * 2) 
  {
    period = Math.round(diff / aMonth);
    unit = 'month';
  } 
  else 
  {
    period = Math.floor(diff / aYear);
    unit = 'year';
  }
  
  let pl = "s";
  if(period == 1)
  {
    pl = "";
    period = (unit != "hour" ? "a" : "an");
  }
  
  let textdate = period + ' ' + unit + pl + ' ago';
  
  return textdate;
}
catch (ex)
{
  alert(ex);
}
}
</script>