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

前端 未结 13 2203
爱一瞬间的悲伤
爱一瞬间的悲伤 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:59

    A filter converting any dates in various ISO-related formats (and who'd use anything else after reading the writings of the Mighty Kuhn?) on standard input to seconds-since-the-epoch time on standard output might serve to illustrate both parts:

    martind@whitewater:~$ cat `which isoToEpoch`
    #!/usr/bin/perl -w
    use strict;
    use Time::Piece;
    # sudo apt-get install libtime-piece-perl
    while (<>) {
      # date --iso=s:
      # 2007-02-15T18:25:42-0800
      # Other matched formats:
      # 2007-02-15 13:50:29 (UTC-0800)
      # 2007-02-15 13:50:29 (UTC-08:00)
      s/(\d{4}-\d{2}-\d{2}([T ])\d{2}:\d{2}:\d{2})(?:\.\d+)? ?(?:\(UTC)?([+\-]\d{2})?:?00\)?/Time::Piece->strptime ($1, "%Y-%m-%d$2%H:%M:%S")->epoch - (defined ($3) ? $3 * 3600 : 0)/eg;
      print;
    }
    martind@whitewater:~$ 
    

提交回复
热议问题