Bug 5549 : DateUtils add subroutine format_sqldatetime
authorColin Campbell <colin.campbell@ptfs-europe.com>
Fri, 17 Jun 2011 13:46:35 +0000 (14:46 +0100)
committerChris Cormack <chrisc@catalyst.net.nz>
Mon, 19 Mar 2012 23:35:40 +0000 (12:35 +1300)
convenience method for a frequent use of the other
methods in the module

Koha/DateUtils.pm
t/DateUtils.t

index 7f4937e..938dc4a 100644 (file)
@@ -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;
index aa0dfcc..9569cfe 100755 (executable)
@@ -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' );