in reply to Finding Time Difference of Localtime

Don't use localtime in the first place. Use time or gmtime and POSIX::strftime instead.

#!/usr/bin/perl use strict; use warnings; use POSIX qw(strftime); my $start = time(); sleep 10; my $end = time(); my $duration = $end - $start; print "It took me $duration seconds\n"; my $start_date = strftime "%Y-%m-%d %H:%M:%S", localtime($start); my $end_date = strftime "%Y-%m-%d %H:%M:%S", localtime($end); print "I was started on $start_date and ended on $end_date\n";

Updated after Aldebaran actually checked the code.

Replies are listed 'Best First'.
Re^2: Finding Time Difference of Localtime
by Aldebaran (Curate) on Dec 01, 2019 at 00:42 UTC
    Don't use localtime in the first place. Use time or gmtime and POSIX::strftime instead.

    I just happened on to this and wonder if this is the behavior that Corion was expecting out of this. This isn't "my thread" or anything; I was just searching (again) for ways to time programs. I'm hoping to find a native one that works on Termux.

    $ ./1.strftime.pl Argument "Sun Dec 1 00:29:42 2019" isn't numeric in subtraction (-) a +t ./1.strftime.pl line 9. Argument "Sun Dec 1 00:29:52 2019" isn't numeric in subtraction (-) a +t ./1.strftime.pl line 9. It took me 0 seconds Usage: POSIX::strftime(fmt, sec, min, hour, mday, mon, year, wday = -1 +, yday = -1, isdst = -1) at ./1.strftime.pl line 11. $ cat 1.strftime.pl #!/usr/bin/perl use strict; use warnings; use POSIX qw(strftime); my $start = gmtime(); sleep 10; my $end = gmtime(); my $duration = $end - $start; print "It took me $duration seconds\n"; my $start_date = strftime "%Y-%m-%d %H:%M:%S", $start; my $end_date = strftime "%Y-%m-%d %H:%M:%S", $end; print "I was started on $start_date and ended on $end_date\n"; $

      Whoops! Thank you for checking this, that's not what I want.

      You want to use time, not gmtime, and use strftime( localtime( $start )) to turn the seconds back into strings.

      I'll fix the above post.

        You want to use time, not gmtime, and use strftime( localtime( $start )) to turn the seconds back into strings.

        That gets us there:

        $ ./2.strftime.pl It took me 10 seconds I was started on 2019-12-03 11:41:38 and ended on 2019-12-03 11:41:48 $ cat 2.strftime.pl
        #!/usr/bin/perl use strict; use warnings; use POSIX qw(strftime); my $start = time(); sleep 10; my $end = time(); my $duration = $end - $start; print "It took me $duration seconds\n"; my $start_date = strftime "%Y-%m-%d %H:%M:%S",(localtime($start)); my $end_date = strftime "%Y-%m-%d %H:%M:%S",(localtime($end)); print "I was started on $start_date and ended on $end_date\n";
        I'll fix the above post.

        Fixing a post from 2010 might have a butterfly effect. Getting better behavior from output is what happens with code review and replication in "the monastery."