skx has asked for the wisdom of the Perl Monks concerning the following question:
Many websites manage to show date differences in a "natural" format. With forum posts, comments, and similar things shown as:
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" ); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Showing the time difference in a natural format? (Time::Duration)
by ikegami (Patriarch) on Sep 21, 2008 at 21:39 UTC | |
by skx (Parson) on Sep 21, 2008 at 21:48 UTC | |
by ikegami (Patriarch) on Sep 21, 2008 at 21:49 UTC | |
|
Re: Showing the time difference in a natural format?
by Anonymous Monk on Sep 22, 2008 at 00:47 UTC |