-3

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?

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Danjel
  • 71
  • 1
  • 7

1 Answers1

1

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.

stevieb
  • 9,065
  • 3
  • 26
  • 36
  • You shouldn't use/recommend strptime() for validation, the implementation accepts values out of range `say Time::Piece->strptime("20150231", "%Y%m%d")->strftime("%Y%m%d");` result's in `20150303`. – chansen Jun 11 '15 at 20:12