Use Perl to Add 2 days to Today
14,368
Solution 1
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
Solution 2
yuu can change the timestamp, which is seconds from epoc
change
my $time = time;
to
my $time = time + 2 * 24 * 60 * 60 ; # 60 seconds 60 minutes 24 hours times 2
Author by
Steven Tharp
Updated on June 11, 2022Comments
-
Steven Tharp about 2 years
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.
-
Steven Tharp over 11 yearsThanks that is exactly what I need
-
Jacob over 11 years@Borodin It is clearer than
my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time()+(2*24*60*60));
. It is also fast-enough that I doubt you would notice the speed difference. -
Borodin over 11 years@BradGilbert: What is wanted is just the epoch time, so
print time() + 172800
is all that is necessary. Efficiency isn't an issue, but I disagree that this version is clear. -
Doug Moscrop over 11 years@Borodin - This version is plenty clear. The only reason it's more 'work' is because it does more than yours - it prints before and after (for demonstration purposes) - if you strip it down to just what is required, it's at most one more call or piece of 'work' than yours. Your answer references a magic number. A built-in one, but one nonetheless.
-
Borodin over 11 years@Doug: Oh come on. The shortest this can be is
use Datetime; print Datetime->now->add(days => 2)->epoch;
which IMO is ridiculous when all that is required isprint time() + 2 * 24 * 60 * 60
. -
Doug Moscrop over 11 years"Oh come on" indeed - the feeling is mutual.
-
Relequestual almost 10 years@StevenTharp If this worked for you, consider accepting the answer =]