How do I convert a date/time to epoch time (unix time/seconds since 1970) in Perl?

前端 未结 13 2156
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 04:20

Given a date/time as an array of (year, month, day, hour, minute, second), how would you convert it to epoch time, i.e., the number of seconds since 1970-01-01 00:00:00 GMT?

13条回答
  •  攒了一身酷
    2020-12-03 04:58

    If you're just looking for a command-line utility (i.e., not something that will get called from other functions), try out this script. It assumes the existence of GNU date (present on pretty much any Linux system):

    #! /usr/bin/perl -w
    
    use strict;
    
    $_ = (join ' ', @ARGV);
    $_ ||= ;
    
    chomp;
    
    if (/^[\d.]+$/) {
        print scalar localtime $_;
        print "\n";
    }
    else {
        exec "date -d '$_' +%s";
    }
    

    Here's how it works:

    $ Time now
    1221763842
    
    $ Time yesterday
    1221677444
    
    $ Time 1221677444
    Wed Sep 17 11:50:44 2008
    
    $ Time '12:30pm jan 4 1987'
    536790600
    
    $ Time '9am 8 weeks ago'
    1216915200
    

提交回复
热议问题