-
-
Save anonymous/ec2059fcf4d591329434 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
diff --git a/lib/Mojo/Date.pm b/lib/Mojo/Date.pm | |
index 5197da4..62ee684 100644 | |
--- a/lib/Mojo/Date.pm | |
+++ b/lib/Mojo/Date.pm | |
@@ -73,6 +73,30 @@ sub to_string { | |
$MONTHS[$month], $year + 1900, $h, $m, $s; | |
} | |
+sub to_words { | |
+ my $self = shift; | |
+ my $to = shift // time; | |
+ | |
+ my $s = int($to - $self->epoch); | |
+ $s = $s * -1 if $s < 0; | |
+ my $m = int($s / 60); | |
+ my $h = int($m / 60); | |
+ my $days = int($h / 24); | |
+ my $years = $days / 365; | |
+ | |
+ return 'less than a minute' if $s < 45; | |
+ return 'about a minute' if $s < 90; | |
+ return "$m minutes" if $m < 45; | |
+ return 'about an hour' if $m < 90; | |
+ return "$h hours" if $h < 24; | |
+ return 'a day' if $h < 42; | |
+ return "$days days" if $days < 30; | |
+ return 'about a month' if $days < 45; | |
+ return "@{[int($days / 30)]} months" if $days < 365; | |
+ return 'about a year' if $years < 1.5; | |
+ return "@{[int $years]} years"; | |
+} | |
+ | |
1; | |
=encoding utf8 | |
@@ -170,6 +194,46 @@ Render date suitable for HTTP messages. | |
# "Sun, 06 Nov 1994 08:49:37 GMT" | |
Mojo::Date->new(784111777)->to_string; | |
+=head2 to_words | |
+ | |
+ my $str = $date->to_words; | |
+ my $str = $date->to_words(784111777); | |
+ | |
+Distance of time in words from now or a specific point in time. | |
+ | |
+ # "less than a minute" | |
+ Mojo::Date->new(time - 1)->to_words; | |
+ | |
+ # "about a minute" | |
+ Mojo::Date->new(time - 50)->to_words; | |
+ | |
+ # "5 minutes" | |
+ Mojo::Date->new(time - 300)->to_words; | |
+ | |
+ # "about an hour" | |
+ Mojo::Date->new(time - 3600)->to_words; | |
+ | |
+ # "3 hours" | |
+ Mojo::Date->new(time - 10800)->to_words; | |
+ | |
+ # "a day" | |
+ Mojo::Date->new(time - 86400)->to_words; | |
+ | |
+ # "4 days" | |
+ Mojo::Date->new(time - 345600)->to_words; | |
+ | |
+ # "about a month" | |
+ Mojo::Date->new(time - 2592000)->to_words; | |
+ | |
+ # "5 months" | |
+ Mojo::Date->new(time - 12960000)->to_words; | |
+ | |
+ # "about a year" | |
+ Mojo::Date->new(time - 33696000)->to_words; | |
+ | |
+ # "3 years" | |
+ Mojo::Date->new(time - 101088000)->to_words; | |
+ | |
=head1 OPERATORS | |
L<Mojo::Date> overloads the following operators. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment