dirtdog has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I'm trying to check if the difference between 2 times is greater than 4 hours. I'm using korn shell, but am trying to use a perl one-liner within the shell script to return the value.

One issue is that one of the times i'm using in the calculation is HH only that is stored in a file. The other time is current HH from unix. So for example, if the HH from the file is 00 and the current HH from unix is 20 the diff is 20, but in reality the time diff is only 4.

Normally, I would include an attempted code snippet, but i just can't come up with anything.

any help is greatly appreciated..thanks

  • Comment on one liner diff between HH military times

Replies are listed 'Best First'.
Re: one liner diff between HH military times
by kennethk (Abbot) on Dec 13, 2013 at 20:05 UTC
    If you just subtract, your valid results would be [20 .. 23, 0 .. 4]. Therefore, if you provide a 4 hour offset and mod by 24, you get the criterion:
    perl -e 'print( ($ARGV[1] - $ARGV[0] + 4) % 24 <= 8, "\n")'
    (or something similar based on your actual, unprovided inputs).

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

      Thanks for the suggestion, but if my inputs are 22 and 02 (so 10PM and 2AM) the one-liner returns 1 and I would expect 4.

      perl -e 'print( ($ARGV[1] - $ARGV[0] + 4) % 24 <= 8, "\n")' 22,02

      am i using the one-liner incorrectly?

        The comma must be replaced by a space to feed @ARGV. Running the command as you did (with warnings produced this.

        C:\Old_Data\perlp>perl -we "print( ($ARGV[1] - $ARGV[0])%24 <=8)" 22,0 +2 Argument "22,02" isn't numeric in subtraction (-) at -e line 1. Use of uninitialized value in subtraction (-) at -e line 1. 1

        With a space instead of comma it produced:

        C:\Old_Data\perlp>perl -we "print( ($ARGV[1] - $ARGV[0])%24 <=8)" 22 0 +2 1

        To get the actual hours difference, remove the <= 8 test.

        C:\Old_Data\perlp>perl -e "print( ($ARGV[1] - $ARGV[0])%24)" 22 02 4
Re: one liner diff between HH military times
by Jim (Curate) on Dec 14, 2013 at 00:03 UTC
    So for example, if the HH from the file is 00 and the current HH from unix is 20 the diff is 20, but in reality the time diff is only 4.

    Says who? I say the difference between 00:00 and 20:00 is 20 hours, not 4 hours. Or maybe I change my mind and say the difference is 748 hours. I'm still right, and you're still wrong.

    The point is you didn't provide any information about what days the two different hours are in or how you're determining which days they're in. Or you neglected to state a critical assumption about your problem.

    Jim