Many websites manage to show date differences in a "natural" format. With forum posts, comments, and similar things shown as:
- "Just now"
- "10 minutes ago".
- "2 months ago".
I've written the following, but it is very naive, and I'm surprised there isn't a CPAN module I could find to do the job properly. Is there anything obvious I've missed, or even a better way to handle this type of problem?
#!/usr/bin/perl -w
use strict;
my $now = time;
my $then = $now - ( 60 * 60 * 6 );
print difference( $now - $then );
sub difference
{
my( $seconds ) = (@_ );
if ( $seconds < 60 )
{
# less than a minute
return( "Just now" );
}
if ( $seconds <= ( 60 * 60 ) )
{
# less than an hour
return( int($seconds/ 60 ) . " minutes ago" );
}
if ( $seconds <= ( 60 * 60 * 24 ) )
{
# less than a day
return( int( $seconds/(60 * 60) ) . " hours ago" );
}
if ( $seconds <= ( 60 * 60 * 24 * 7 ) )
{
# less than a week
return( int( $seconds/(60*60*24)) . " days ago" );
}
# fall-back weeks ago
return( int( $seconds/(60*60*24*7)) . " weeks ago" );
}