in reply to Ctime/Mtime compare with string date

You'll probably have to parse the string date, and compare that to what localtime or gmtime make of the timestamp.

  • Comment on Re: Ctime/Mtime compare with string date

Replies are listed 'Best First'.
Re^2: Ctime/Mtime compare with string date
by bimleshsharma (Beadle) on Jan 18, 2012 at 13:40 UTC

    Thanks, I created subroutine to do this that will return -1 if lesser, 0 for equal and 1 for greater.

    sub Date_Comp { my %months= {Jan => 1,Feb => 2,Mar => 3,Apr => 4,May => 5,Jun => +6,Jul => 7,Aug => 8,Sep => 9,Oct => 10,Nov => 11,Dec => 12}; my($date1, $date2)= @_; my @dates1= split (" ",$date1); my @dates2= split (" ",$date2); my @times1= split (":",$dates1[3]); my @times2= split (":",$dates2[3]); my $days1= $dates1[4]*365 + $months{$dates1[1]}*30 + $dates1[2];p +rint "\ndays1= $days1"; my $days2= $dates2[4]*365 + $months{$dates2[1]}*30 + $dates2[2];p +rint "\ndays2= $days2"; my $time1= $times1[0]*60*60 + $times1[1]*60 + $times1[2]; print " +\ntimes1= $time1"; my $time2= $times2[0]*60*60 + $times2[1]*60 + $times2[2]; print " +\ntimes2= $time2"; if ($days1 > $days2) { print "\n $date1 is latest \n"; return 1 } elsif ($days1 < $days2) { print "\n $date2 is latest \n"; return -1 } elsif ($days1 == $days2) { if ($time1>$time2) {print "\n $date1 is latest \n"; return 1 } elsif($time1<$time2) {print "\n $date2 is older \n"; return -1} elsif($time1 == $time2) {print "\n Both are same \n"; return 0 } } }
      Some years (leap years) have an extra day and not all months have 30 days. I think this will affect your calculations. The time functions that go back and forth to epoch time know about these details.

      Another technique is that if you can get the date/time string to look like this: "2011-10-01 1601" or similar, you can just use: $datetime1 cmp $datetime2. The key is that you need leading zeroes for the dates and times or the ascii sort order won't work out (07:02 is not the same as 7:02).

      You will be ok on mtime, but see AnonMonk's post re:ctime.