Validating a date in a file on SunOS 5.10

119 views Asked by At

I have a file with a list of dates in the format below: yyyymmddhhmmss

20150608141617
20150608141345
20150608141649
20150608141506
20150608141618
20150608141545

Would like to validate the correctness of these dates in case there are errors during generation in a previous process.

Correctness means that there are no spaces,length is 14 characters and the date is valid i.e. no date like 20151508141545.

Is this possible in perl or bash?

1

There are 1 answers

1
stevieb On

The following will do what you need, using a quick check for length, then the built-in Time::Piece module to validate correctness.

#!/usr/bin/perl

use warnings;
use strict;

use Time::Piece;

for my $entry (<DATA>){
    chomp $entry;

    next if length($entry) > 14;

    my $date;

    eval {
        $date = Time::Piece->strptime($entry, "%Y%m%d%H%M%S");
    };
    if ($@){
        next;
    }

    print "$date\n";
}

__DATA__
20150608141617
20152525252525
201506081413454
20150608141649
20150608141506
20150608141618
20150608141545

To change this code to read from a file, above the for() loop, write:

open my $fh, '<', 'filename.txt'
  or die "Can't open the file: $!";

Then in the for() loop, change <DATA> to <$fh> and delete __DATA__ and everything below it.