| 1 | package Data::Quantity::Time::DurationSeconds; | ||
| 2 | |||
| 3 | require 5; | ||
| 4 | use strict; | ||
| 5 | use Carp; | ||
| 6 | |||
| 7 | use vars qw( $VERSION ); | ||
| 8 | $VERSION = 0.001; | ||
| 9 | |||
| 10 | use Data::Quantity::Number::Integer '-isasubclass'; | ||
| 11 | |||
| 12 | # undef = Data::Quantity::Time::DurationSeconds->scale(); | ||
| 13 | sub scale { | ||
| 14 | return 'Seconds'; | ||
| 15 | } | ||
| 16 | |||
| 17 | sub type { | ||
| 18 | return 'temporal', 'duration'; | ||
| 19 | } | ||
| 20 | |||
| 21 | use vars qw( $default_readable_format ); | ||
| 22 | $default_readable_format ||= 'h:m:s'; | ||
| 23 | |||
| 24 | # $value = Data::Quantity::Time::DurationSeconds->readable_value($number) | ||
| 25 | # $value = Data::Quantity::Time::DurationSeconds->readable_value($number, $style) | ||
| 26 | sub readable_value { | ||
| 27 | my $class_or_item = shift; | ||
| 28 | my $value = shift; | ||
| 29 | $class_or_item->new($value)->readable(@_); | ||
| 30 | } | ||
| 31 | |||
| 32 | # $string = $quantity->readable( @_ ); | ||
| 33 | sub readable { | ||
| 34 | my $duration_q = shift; | ||
| 35 | my $style = shift; | ||
| 36 | $style ||= $default_readable_format; | ||
| 37 | my $seconds = $duration_q->value or return; | ||
| 38 | |||
| 39 | if ( $style eq 's' ) { | ||
| 40 | return $seconds; | ||
| 41 | } elsif ( $style eq 'h:m:s' ) { | ||
| 42 | my $minutes = int($seconds / 60) and $seconds %= 60; | ||
| 43 | my $hours = int($minutes / 60) and $minutes %= 60; | ||
| 44 | if( $hours ) { | ||
| 45 | my $mm = $minutes; | ||
| 46 | my $ss = $seconds; | ||
| 47 | foreach ( $mm, $ss ) { | ||
| 48 | $_ = ( '0' x ( 2 - length($_) ) ) . $_; | ||
| 49 | } | ||
| 50 | return $hours . ':' . $mm . ':' . $ss; | ||
| 51 | } else { | ||
| 52 | my $ss = $seconds; | ||
| 53 | foreach ( $ss ) { | ||
| 54 | $_ = ( '0' x ( 2 - length($_) ) ) . $_; | ||
| 55 | } | ||
| 56 | return ( $minutes || '0' ) . ':' . $ss; | ||
| 57 | } | ||
| 58 | } else { | ||
| 59 | croak "Unkown duration readable format: '$style'"; | ||
| 60 | } | ||
| 61 | } | ||
| 62 | |||
| 63 | 1; |