Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Perl to Add 2 days to Today

Tags:

time

perl

I want to use perl and add two days from today and output this as a unix time. I have found lots of information on how to convert Unix time to readable time but I need the ouput to be a unix time. I found this

my $time = time;    # or any other epoch timestamp 
my @months = ("Jan","Feb","Mar","Apr","May","Jun","Jul",
              "Aug","Sep","Oct","Nov","Dec");
my ($sec, $min, $hour, $day,$month,$year) = (localtime($time))[0,1,2,3,4,5]; 
# You can use 'gmtime' for GMT/UTC dates instead of 'localtime'
print "Unix time ".$time." converts to ".$months[$month].
      " ".$day.", ".($year+1900);

How do I take current time and add 2 days and output as Unix time.

like image 307
Steven Tharp Avatar asked Feb 23 '13 16:02

Steven Tharp


1 Answers

Have you considered using the DateTime package? It contains a lot of date manipulation and computation routines, including the ability to add dates.

There is an FAQ, with examples, here (in particular, see the section on sample calculations and DateTime formats).

Here is a snippet:

use strict;
use warnings;

use DateTime;

my $dt = DateTime->now();
print "Now: " . $dt->datetime() . "\n";
print "Now (epoch): " . $dt->epoch() . "\n";

my $two_days_from_now = $dt->add(days => 2);
print "Two days from now: " . $two_days_from_now->datetime() . "\n";
print "Two days from now (epoch): " . $two_days_from_now->epoch() . "\n";

Which produces the following output:

Now: 2013-02-23T18:30:58
Now (epoch): 1361644258
Two days from now: 2013-02-25T18:30:58
Two days from now (epoch): 1361817058
like image 145
mkaliszan Avatar answered Sep 18 '22 01:09

mkaliszan