Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re^2: Ctime/Mtime compare with string date

by bimleshsharma (Beadle)
on Jan 18, 2012 at 13:40 UTC ( #948548=note: print w/replies, xml ) Need Help??

in reply to Re: Ctime/Mtime compare with string date
in thread Ctime/Mtime compare with string date

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 } } }

Replies are listed 'Best First'.
Re^3: Ctime/Mtime compare with string date
by Marshall (Abbot) on Jan 18, 2012 at 14:19 UTC
    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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://948548]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2017-10-17 07:54 GMT
Find Nodes?
    Voting Booth?
    My fridge is mostly full of:

    Results (222 votes). Check out past polls.