by Matt Coughlin

getTimeAgo:

Goal:

Estimate how long ago an action occurred (e.g., "2 months ago").

The value can be calculated relative to the present time or relative to any point in the past.

Example:

Event Date:

: o'clock

Choose a Day:

: o'clock

Implementation notes:

HTML:

<select size="1" name="eventMonth" id="eventMonth">...</select>
<select size="1" name="eventDay" id="eventDay">...</select>
<select size="1" name="eventYear" id="eventYear">...</select>
<input type="button" value="Get Time Ago" id="timeAgo"/>

<select size="1" name="pastMonth" id="pastMonth">...</select>
<select size="1" name="pastDay" id="pastDay">...</select>
<select size="1" name="pastYear" id="pastYear">...</select>
<input type="button" value="Get Time Ago From This Date" id="timeAgoFromPast"/>
        

JavaScript:

// Get time ago, as of right now.
$('#timeAgo').click(function(){
    var eventYear = $('#eventYear').val();
    var eventMonth = $('#eventMonth').get(0).selectedIndex;
    var eventDay = $('#eventDay').get(0).selectedIndex + 1;
    var eventHour = $('#eventHour').get(0).selectedIndex + 1;
    var eventMinute = $('#eventMinute').get(0).selectedIndex + 1;

    var eventDate = new Date(eventYear, eventMonth, eventDay, eventHour, eventMinute);
    var timeAgo = new Date().getTimeAgo(eventDate);
    var text = timeAgo.value + ' ' + timeAgo.units + ' ago.';
    alert(text);
});

// Get time ago, as of a specified date in the past.
$('#timeAgoFromPast').click(function(){
    var eventYear = $('#eventYear').val();
    var eventMonth = $('#eventMonth').get(0).selectedIndex;
    var eventDay = $('#eventDay').get(0).selectedIndex + 1;
    var eventHour = $('#eventHour').get(0).selectedIndex + 1;
    var eventMinute = $('#eventMinute').get(0).selectedIndex + 1;

    var pastYear = $('#pastYear').val();
    var pastMonth = $('#pastMonth').get(0).selectedIndex;
    var pastDay = $('#pastDay').get(0).selectedIndex + 1;
    var pastHour = $('#pastHour').get(0).selectedIndex + 1;
    var pastMinute = $('#pastMinute').get(0).selectedIndex + 1;

    var eventDate = new Date(eventYear, eventMonth, eventDay, eventHour, eventMinute);
    var pastDate = new Date(pastYear, pastMonth, pastDay, pastHour, pastMinute);
    var timeAgo = pastDate.getTimeAgo(eventDate);
    var text = timeAgo.value + ' ' + timeAgo.units + ' ago.';
    alert(text);
});
        

getTimeAgo.js