“Time ago” formatting in ASP classic

Today, I needed to convert a time stamp like “1/25/2011 10:42:11 AM” to a readable sentence format like “2 months and 6 hours ago.” Here’s the code I came up with:


	function timeAgo( byval time )
		sentence = ""
		hits = 0
		piecesAgo = array( 0, 0, 0, 0, 0, 0 )
		piecesTotals = array( 0, 12, 30, 24, 60, 60 )
		labels = array( "year", "month", "day", "hour", "minute", "second" )
		dateAddSymbols = array( "yyyy", "m", "d", "h", "n", "s" )

		for p=0 to uBound( piecesAgo )
			piecesAgo( p ) = 0 + datediff( dateAddSymbols( p ), time, now( ))

			if piecesAgo( p ) <> 0 then
				time = dateAdd( dateAddSymbols( p ), piecesAgo( p ), time )
			end if
		next

		'remove negative values
		for p=uBound( piecesAgo ) to 0 step -1
			if piecesAgo( p ) < 0 and p > 0 then
				piecesAgo( p ) = piecesAgo( p ) + piecesTotals( p )
				piecesAgo( p-1 ) = piecesAgo( p-1 ) - 1
			end if
		next

		for p=0 to uBound( piecesAgo )
			if piecesAgo( p ) <> 0 then

				if len( sentence ) > 0 then
					sentence = sentence & " and "
				end if
				sentence = sentence & piecesAgo( p ) & " " & labels( p )
				if piecesAgo( p ) > 1 then
					sentence = sentence & "s"
				end if
				hits = hits + 1
				if hits >= 2 then
					exit for
				end if
			end if
		next

		set piecesAgo = nothing
		set piecesTotals = nothing
		set labels = nothing
		set dateAddSymbols = nothing

		timeAgo = sentence & " ago"
	end function