Skip to content

Commit

Permalink
Merge pull request #17 from yewtc/master
Browse files Browse the repository at this point in the history
Negative Seconds with fractional seconds had the wrong sign
  • Loading branch information
lestrrat committed Mar 15, 2021
2 parents e1bbb3c + 4696310 commit b027aa4
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 6 deletions.
9 changes: 5 additions & 4 deletions lib/DateTime/Format/Pg.pm
Expand Up @@ -592,7 +592,7 @@ sub parse_duration {

$string =~ s/\b(\d+):(\d\d):(\d\d)(\.\d+)?\b/$1h $2m $3$4s/g;
$string =~ s/\b(\d+):(\d\d)\b/$1h $2m/g;
$string =~ s/(-\d+h)\s+(\d+m)\s+(\d+s)\s*/$1 -$2 -$3 /;
$string =~ s/(-\d+h)\s+(\d+m)\s+(\d+(?:\.\d+)?s)\s*/$1 -$2 -$3 /;
$string =~ s/(-\d+h)\s+(\d+m)\s*/$1 -$2 /;

while ($string =~ s/^\s*(-?\d+(?:[.,]\d+)?)\s*([a-zA-Z]+)(?:\s*(?:,|and)\s*)*//i) {
Expand Down Expand Up @@ -626,10 +626,11 @@ sub parse_duration {
}

# From the spec, Pg can take up to 6 digits for fractional part
# (duh, as 1 sec = 1_000_000 nano sec). If we're missing 0's,
# that is microseconds. If we're missing 0's,
# we should pad them
$fractional .= '0'x (6 - length($fractional));
push @extra_args, ("nanoseconds" => $fractional);
$fractional .= '0'x (9 - length($fractional));
my $sign = ($amount > 0) ? 1 : -1;
push @extra_args, ("nanoseconds" => $sign * $fractional);
}

$du->$arith_method($base_unit => $amount * $num, @extra_args);
Expand Down
4 changes: 2 additions & 2 deletions t/gh12.t
Expand Up @@ -15,6 +15,6 @@ if (! ok !$e, "should succeed parsing '$offset' without errors") {
}

is $duration->seconds, 28, "seconds should be '28'";
is $duration->nanoseconds, 369220, "seconds should be '369220'";
is $duration->nanoseconds, 369220000, "nano-seconds should be '369220000'";

done_testing;
done_testing;
7 changes: 7 additions & 0 deletions t/parse_interval.t
Expand Up @@ -33,6 +33,13 @@ BEGIN
[ '-1 days' => DateTime::Duration->new(days => -1) ],
[ '-23:59' => DateTime::Duration->new(hours => -23, minutes => -59) ],
[ '-1 days -00:01' => DateTime::Duration->new( days => -1, minutes => -1) ],
[ '-1 days -20:30:56.123456' => DateTime::Duration->new(
days => -1,
minutes => -1230, # = 20 * 60 + 30
seconds => -56,
nanoseconds => -123456000,
),
],
[ '1 mon -1 days' => DateTime::Duration->new(months => 1)->add(days => -1) ],
[ '1 day 1 month' => DateTime::Duration->new(months => 1)->add(days => 1) ],
[ '1 month -1 days' => DateTime::Duration->new(months => 1)->add(days => -1) ],
Expand Down

0 comments on commit b027aa4

Please sign in to comment.