From 8cc5b3452eb9b5d06505192a5cabdcd1bb28a084 Mon Sep 17 00:00:00 2001 From: Colin Campbell Date: Fri, 17 Jun 2011 14:46:35 +0100 Subject: [PATCH] Bug 5549 : DateUtils add subroutine format_sqldatetime convenience method for a frequent use of the other methods in the module --- Koha/DateUtils.pm | 22 +++++++++++++++++++++- t/DateUtils.t | 9 ++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/Koha/DateUtils.pm b/Koha/DateUtils.pm index 7f4937ed34..938dc4a454 100644 --- a/Koha/DateUtils.pm +++ b/Koha/DateUtils.pm @@ -26,7 +26,7 @@ use C4::Context; use base 'Exporter'; use version; our $VERSION = qv('1.0.0'); -our @EXPORT = (qw( dt_from_string output_pref)); +our @EXPORT = (qw( dt_from_string output_pref format_sqldatetime)); =head1 DateUtils @@ -122,4 +122,24 @@ sub output_pref { return; } +=head2 format_sqldatetime + +$string = format_sqldatetime( $string_as_returned_from_db ); + +a convenience routine for calling dt_from_string and formatting the result +with output_pref as it is a frequent activity in scripts + +=cut + +sub format_sqldatetime { + my $str = shift; + my $force_pref = shift; # if testing we want to override Context + if ( defined $str && $str =~ m/^\d{4}-\d{2}-\d{2}/ ) { + my $dt = dt_from_string( $str, 'sql' ); + $dt->truncate( to => 'minutes' ); + return output_pref( $dt, $force_pref ); + } + return q{}; +} + 1; diff --git a/t/DateUtils.t b/t/DateUtils.t index aa0dfcc0ea..9569cfe4cb 100755 --- a/t/DateUtils.t +++ b/t/DateUtils.t @@ -5,7 +5,7 @@ use DateTime; use DateTime::TimeZone; use C4::Context; -use Test::More tests => 19; # last test to print +use Test::More tests => 21; # last test to print BEGIN { use_ok('Koha::DateUtils'); } @@ -67,3 +67,10 @@ cmp_ok( $dt0->ymd(), 'eq', $ymd, 'Returned object corrects iso day 0' ); # Return undef if passed mysql 0 dates $dt0 = dt_from_string( '0000-00-00', 'iso' ); is( $dt0, undef, "undefined returned for 0 iso date" ); + +my $formatted = format_sqldatetime( '2011-06-16 12:00:07', 'metric' ); +cmp_ok( $formatted, 'eq', '16/06/2011 12:00', 'format_sqldatetime conversion' ); + +$formatted = format_sqldatetime( undef, 'metric' ); +cmp_ok( $formatted, 'eq', q{}, + 'format_sqldatetime formats undef as empty string' ); -- 2.39.5