Bug 33159: Simplify ES handling and fix zebra handling
[srvgit] / Koha / DateUtils.pm
index ad242b5..2ee889a 100644 (file)
@@ -30,6 +30,7 @@ BEGIN {
         dt_from_string
         output_pref
         format_sqldatetime
+        flatpickr_date_format
     );
 }
 
@@ -142,9 +143,10 @@ sub dt_from_string {
         die "Invalid dateformat parameter ($date_format)";
     }
 
-    # Add the faculative time part [hh:mm[:ss]]
-    my $time_re .= qr|
+    # Add the facultative time part including time zone offset; ISO8601 allows +02 or +0200 too
+    my $time_re = qr{
             (
+                [Tt]?
                 \s*
                 (?<hour>\d{2})
                 :
@@ -157,11 +159,18 @@ sub dt_from_string {
                     \s
                     (?<ampm>\w{2})
                 )?
+                (
+                    (?<utc>[Zz]$)|((?<offset>[\+|\-])(?<hours>[01][0-9]|2[0-3]):?(?<minutes>[0-5][0-9])?)
+                )?
             )?
-    |xms;
+    }xms;
     $regex .= $time_re unless ( $date_format eq 'rfc3339' );
     $fallback_re .= $time_re;
 
+    # Ensure we only accept date strings and not other characters.
+    $regex = '^' . $regex . '$';
+    $fallback_re = '^' . $fallback_re . '$';
+
     my %dt_params;
     my $ampm;
     if ( $date_string =~ $regex ) {
@@ -174,9 +183,12 @@ sub dt_from_string {
             second => $+{second},
         );
         $ampm = $+{ampm};
+        if ( $+{utc} ) {
+            $tz = DateTime::TimeZone->new( name => 'UTC' );
+        }
         if ( $+{offset} ) {
             # If offset given, set inbound timezone using it.
-            $tz = DateTime::TimeZone->new( name => $+{offset} . $+{hours} . $+{minutes} );
+            $tz = DateTime::TimeZone->new( name => $+{offset} . $+{hours} . ( $+{minutes} || '00' ) );
         }
     } elsif ( $do_fallback && $date_string =~ $fallback_re ) {
         %dt_params = (
@@ -282,7 +294,7 @@ sub output_pref {
     # FIXME: see bug 13242 => no TZ for dates 'infinite'
     if ( $dt->ymd !~ /^9999/ ) {
         my $tz = $dateonly ? DateTime::TimeZone->new(name => 'floating') : C4::Context->tz;
-        $dt->set_time_zone( $tz );
+        eval { $dt->set_time_zone( $tz ); }
     }
 
     my $pref =
@@ -365,4 +377,26 @@ sub format_sqldatetime {
     return q{};
 }
 
+=head2 flatpickr_date_format
+
+$date_format = flatpickr_date_format( $koha_date_format );
+
+Converts Koha's date format to Flatpickr's. E.g. 'us' returns 'm/d/Y'.
+
+If no argument is given, the dateformat preference is assumed.
+
+Returns undef if format is unknown.
+
+=cut
+
+sub flatpickr_date_format {
+    my $arg = shift // C4::Context->preference('dateformat');
+    return {
+        us     => 'm/d/Y',
+        metric => 'd/m/Y',
+        dmydot => 'd.m.Y',
+        iso    => 'Y-m-d',
+    }->{$arg};
+}
+
 1;