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

Is there a Perl function/routine that would take the number of seconds from say, January 1, 2000 and convert them into a date?

Replies are listed 'Best First'.
Re: seconds into a date
by davorg (Chancellor) on Jul 01, 2009 at 14:45 UTC

    localtime takes a number of seconds since the epoch (usually 1st Jan 1970) and returns information about the date and time.

    For more complex requirements, I recommend looking at DateTime.

    #!/usr/bin/perl use strict; use warnings; use DateTime; # 1st Jan 2000 my $date = DateTime->new(year => 2000, month => 1, day => 1); # Add a million seconds $date->add(seconds => 1_000_000); # See what you get - 2000-01-12T13:46:40 print $date;

    Update: Actually you can also do something similar using only modules from the standard distribution.

    #!/usr/bin/perl use strict; use warnings; use Time::Local; # Warning: The parameters to timelocal can be a bit confusing # Read the documentation carefully my $date = timelocal(0, 0 , 0, 1, 0, 100); $date += 1_000_000; print scalar localtime $date;
    --

    See the Copyright notice on my home node.

    Perl training courses

      ..thanks so much 'davorg' - your first response worked great and I'll try your update as well as look at DateTime although that looks like quite a bit of documentation... again, thanks....
Re: seconds into a date
by jrsimmon (Hermit) on Jul 01, 2009 at 14:50 UTC
    By using the number of seconds since the epoch, you can use:
    my (@date) = localtime($numSeconds);
    See the time and localtime data in perldoc.
Re: seconds into a date
by toolic (Bishop) on Jul 01, 2009 at 15:30 UTC
Re: seconds into a date
by mzedeler (Pilgrim) on Jul 01, 2009 at 21:53 UTC

    localtime and friends use UNIX time which is not a completely accurate measure of how many seconds has passed since 1970. It is very easy to use, but your results will be slightly off because of the way leap seconds are treated, see Unix time.

    I am not aware of any perl module that does positively treats leap seconds correctly.

      I am not aware of any perl module that does positively treats leap seconds correctly.

      DateTime seems to have proper leap second support, at least it has and uses a table of all leap seconds.

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
        Be aware, however, that there is no implementation of leap seconds which can be valid for all jurisdictions. See an example in javascript here http://www.ucolick.org/~sla/leapsecs/epochtime.html