Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time difference in seconds

In a Perl program I have a variable containing date / time in this format:

Feb 3 12:03:20  

I need to determine if that date is more than x seconds old (based on current time), even if this occurs over midnight (e.g. Feb 3 23:59:00 with current time = Feb 4 00:00:30).

The perl date / time information I've found is mind-boggling. Near as I can tell I need to use Date::Calc, but I am not finding a seconds-delta. Thanks :)

like image 330
Xi Vix Avatar asked Feb 03 '12 20:02

Xi Vix


People also ask

How do you calculate time difference in seconds?

To get the total seconds between two times, you multiply the time difference by 86400, which is the number of seconds in one day (24 hours * 60 minutes * 60 seconds = 86400).

How do you calculate time duration?

Calculate the duration between two times First, identify the starting and an ending time. The goal is to subtract the starting time from the ending time under the correct conditions. If the times are not already in 24-hour time, convert them to 24-hour time. AM hours are the same in both 12-hour and 24-hour time.

How do I calculate seconds from minutes?

To convert a minute measurement to a second measurement, multiply the time by the conversion ratio. The time in seconds is equal to the minutes multiplied by 60.

What is time difference?

(taɪm ˈdɪfrəns ) noun. the difference in clock time between two or more different time zones.


2 Answers

#!/usr/bin/perl

my $Start = time();
sleep 3;
my $End = time();
my $Diff = $End - $Start;

print "Start ".$Start."\n";
print "End ".$End."\n";
print "Diff ".$Diff."\n";

This is a simple way to find the time difference in seconds.

like image 122
Sjoerd Linders Avatar answered Oct 29 '22 13:10

Sjoerd Linders


In the spirit of TMTOWTDI, you can leverage the core Time::Piece :

#!/usr/bin/env perl
use strict;
use warnings;
use Time::Piece;
my $when = "@ARGV" or die "'Mon Day HH:MM:SS' expected\n";
my $year = (localtime)[5] + 1900;
my $t = Time::Piece->strptime( $year . q( ) . $when, "%Y %b %d %H:%M:%S" );
print "delta seconds = ", time() - $t->strftime("%s"),"\n";

$ ./mydelta Feb 3 12:03:20

delta seconds = 14553

The current year is assumed and taken from your localtime.

like image 43
JRFerguson Avatar answered Oct 29 '22 13:10

JRFerguson