Skip to content

Commit

Permalink
Begin working on internal date parser
Browse files Browse the repository at this point in the history
  • Loading branch information
mdom committed Jun 30, 2018
1 parent 6a812c7 commit 5af823e
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
70 changes: 70 additions & 0 deletions lib/StrptimePP.pm
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package StrptimePP;
use strict;
use warnings;
use parent 'Exporter';
use Time::Local 'timelocal';
use Carp 'croak';

our @EXPORT_OK = qw(compile strptime);

## TODO prefer past

sub strptime {
my ( $string, $format ) = @_;
my @now = localtime;
my $re = compile($format);
if ( $string =~ $re ) {
my %match = %+;
if ( $match{month} ) {
$match{month}--;
}
return timelocal(
$match{seconds} || 0,
$match{minutes} || 0,
$match{hours} || 0,
$match{day} || $now[3],
$match{month} || $now[4],
$match{year} || $now[5],
);
}
return;
}

my %patterns = (
'%' => '%',
H => '(?<hours>(?:[01][0-9])|(?:2[0-3]))',
M => '(?<minutes>[0-5][0-9])',
S => '(?<seconds>[0-5][0-9])',

d => '(?<day> 0[1-9] | [12][0-9] | 3[01] )',

m => '(?<month>(?:0[1-9])|(?:1[012]))',
Y => '(?<year>\d{4})',
);

sub compile {
my ($format) = @_;
my $re = '';
while (1) {
if ( $format =~ /\G%(.)/gcx ) {
if ( exists $patterns{$1} ) {
$re .= $patterns{$1};
}
else {
croak "Unknown conversion specification $1\n";
}
}
elsif ( $format =~ /\G(.+?)(?=%)/gcx ) {
$re .= "\Q$1\E";
}
elsif ( $format =~ /\G(.+?)$/gcx ) {
$re .= "\Q$1\E";
}
else {
last;
}
}
return qr($re)x;
}

1;
19 changes: 19 additions & 0 deletions t/11strptime.t
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#/usr/bin/perl

use strict;
use warnings;
use Test::More;
use StrptimePP qw(compile strptime);

$ENV{TZ} = 'GMT';

is( compile("%%"), qr(%)x );
is( compile("foo"), qr(foo)x );
is( compile("foo*"), qr(foo\*)x );

eval { strptime( '2018-06-30T12:12:12', '%1' ) };
like( $@, qr(^Unknown conversion specification 1) );

is( strptime( '2018-06-30T12:12:12', '%Y-%m-%dT%H:%M:%S' ), 1530360732 );

done_testing;

0 comments on commit 5af823e

Please sign in to comment.