Skip site navigation (1)Skip section navigation (2)
Date:      19 Nov 2001 12:04:16 -0800
From:      Ken McGlothlen <mcglk@artlogix.com>
To:        <freebsd-questions@freebsd.org>
Subject:   Re: Epoch Time on Freebsd with perl
Message-ID:  <87n11i34u7.fsf@ralf.artlogix.com>
In-Reply-To: <NEBBJFKEHEOLHKCGOHFOCECMDMAA.simon.g@claycrossbs.co.uk>
References:  <NEBBJFKEHEOLHKCGOHFOCECMDMAA.simon.g@claycrossbs.co.uk>

next in thread | previous in thread | raw e-mail | index | archive | help
Someone whose name has been removed to protect the innocent writes:

| > [Chris Aitken writes]
| > $date1 = "2001-10-01 01:00:00";
| > $date2 = "2001-10-01 03:00:00";
| >
| > What I want is to somehow calculate that there is 2 hours between these 2
| > dates (or 120 minutes, or 7200 seconds etc etc) [in Perl]
| > Any help on this would be appreciated.
| 
| Depending on your database you could do this in SQL, I would recommend
| RTFMing its docs.

That deserves *some* kind of prize for possibly the least efficient solution to
a problem ever posted on the list.

There are several methods out there.  One of them would be this:

        use Time::Local;

        sub parsetime {
                # Get the date from the parameter list.

                my( $datestring ) = shift;

                # Break up the date on all non-digit characters, and reverse
                # the order of the result.  You'll now have [second, minute,
                # hour, day, month, year] stored in @date.

                my( @date ) = reverse( split( /\D+/, $datestring ) );

                # Due to a quick in Time::Local, months range from 0..11, so
                # subtract one from the month.

                $date[4]--;

                # Now we let timelocal() (in Time::Local) do the work and
                # return the result.

                return( timelocal( @date ) );
        }

Christ, this assumes that your dates are going to be in the above format.  Once
you have this routine defined, you can find out the difference between any two
dates by using this (assuming the $date1 and $date2 definitions you have
above):

        $time1 = &parsetime( $date1 );
        $time2 = &parsetime( $date2 );
        $difference = $time2 - $time1;

In fact, there are a bunch of Perl modules out there which are useful for this
sort of thing.  This is just a relatively efficient one, because you know the
format of the dates you're parsing.  For really weird ones, you can go as far
as using Time::ParseDate, which is slow, but incredibly flexible.

To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-questions" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?87n11i34u7.fsf>