Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


add date in perl

Posted on 2004-09-18
Medium Priority
Last Modified: 2008-01-09
please tell me how to add date in perl.
sample : 01/01/2004+14 => 14/01/2004
Question by:divt
  • 3
  • 3
  • 2
  • +2
LVL 36

Expert Comment

ID: 12090966
Hi divt,

Er... so you want it like 14/01/2004?

LVL 36

Expert Comment

ID: 12090967
Oh wait, you're doing dd/mm/yy right?

LVL 48

Expert Comment

ID: 12091011
Where does your initial date (dd/mm/yyyy) come from?

Depending on how/where it comes from, depends on the complexity of the answer.
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

LVL 85

Assisted Solution

ozo earned 80 total points
ID: 12091021
use Date::Manip;
print UnixDate(DateCalc("01/01/2004","+14d",\$err),"%d/%m/%Y");

Author Comment

ID: 12091251
I apologize for not making it clear as it 's been a long night!!!

I was able to solve my problem with this piece of code:

use Date::Parse;
use Date::Format;

$BeginDate = '01/01/2004';
$DaysWait = 14;

$EndDate = DateAdd($BeginDate, $DaysWait);

print "From date $BeginDate , wait $DaysWait days before $EndDate.\n";


sub DateAdd {

    ($BeginDate, $DaysWait) = @_;

    $BeginDateEpoch = str2time($BeginDate);
    $DaysWaitEpoch = $DaysWait * 86400;

    $EndDateEpoch = $BeginDateEpoch + $DaysWaitEpoch;

return time2str('%d/%m/%Y', $EndDateEpoch);

Still need to work on it though.  Any way, thanks everyone for your input.  I haven't tested ozo 's suggestion.  But what does the \$err do ?

Author Comment

ID: 12091258
And yes, the question was wrong.  It should read

sample : 01/01/2004+14 => 15/01/2004

with the above code, it gives this:

$perl dateadd.pl
From date 01/01/2004 , wait 14 days before 15/01/2004


Accepted Solution

ZiaTioN earned 920 total points
ID: 12093453
I do not like using third party modules whenever possible. Especially if you can code it yourself! =P

Here is some quick code I whipped up that performs exactly what you are looking for and with no modules.

#!/usr/bin/perl -w

use strict;  # Always a must for all decent perl programs!

my $sDate = '01/01/2004';  # Start Date
my $inc   = '1000000';     # Number to increment by

my @months = qw(Jan=31 Feb=28 Mar=31 Apr=30 May=31 Jun=30
                Jul=31 Aug=31 Sep=30 Oct=31 Nov=30 Dec=31);  # Array of months and days

my ($day, $month, $year) = split(/\//, $sDate);      # Splitting of start date into each element
my ($m, $mTotal) = split(/\=/, $months[$month-1]);   # Extracting initial months total days

$day += $inc;                # Adding incremental value to start day
while ($day > $mTotal) {   # Start of incrementing while loop
   $day -= $mTotal;        # Subtracts $mTotal from $day to increment month
   $month++;               # Increments month

   if ($month > ($#months+1)) {  # Checks if $month value is larger than 12
      $month -= ($#months+1);    # Subtracts 12 from the value of $month
      $year++;                   # Increments year value
   ($m, $mTotal) = split(/\=/, $months[$month-1]);  # Extracts next months total days

$day   = sprintf("%02s", $day);      # Prepends value of $day with 0's if the total digits are < 2
$month = sprintf("%02s", $month);    # Prepends value of $month with 0's if the total digits are < 2
$year  = sprintf("%04s", $year);     # Prepends value of $year with 0's if the total digits are < 4
print "New date is: ".$day."/".$month."/".$year."\n";   # Prints new date

Hope this helps you. I tried to over comment this piece so you and others could follow it and see what it is doing at every stage.

Author Comment

ID: 12094732

I share the same thought of not using 3rd party modules.  Your code is logical, functional, and concise. Although I suspect we don't need this line at the end of while loop:

($m, $mTotal) = split(/\=/, $months[$month-1]);  # Extracts next months total days

Thank you everyone for your inputs.

Please see my other question, if you are interested:

calculate number of days between 2 dates (without external modules)


Expert Comment

ID: 12097359

The line of code in question is more than needed, it is essential. This line makes sure the script moves to the next month therefore using the correct value of days for the right month since $month was incremented prior to this. Without this line the value of "31" would be used for every month of the year since that was the initial value loaded into $month before the while loop. This value is the value of Jan in the array.

Comment this line out and run the script you will see what I mean. If you start on Jan 1 2004 and enter 365 days as the $inc value the script will tell you the ending date is Dec 24 2004 when this is incorrect. It gets this because it used 31 for each months value. With this line as it is (uncommented) the script tells you that 365 days from Jan 1 2004 is Jan 1 2005 which is the correct answer.
LVL 48

Expert Comment

ID: 12097695
Here's a much neater (IMHO) and shorter solution that uses no third party modules.  I also handles leap years correctly :-)

use strict;
use Time::Local;
use POSIX 'strftime';

my $inc=14;
my $date='01/01/2004';
my ($d,$m,$y) = split(/\//,$date);

print strftime "New date is %d/%m/%Y\n", localtime timelocal(0,0,0,$d,$m-1,$y) + ($inc * 24 * 60 * 60);

Expert Comment

ID: 12097986
I think the idea was to not use any modules. Even ones included in the standard distrobution. Since I posted this 2 days ago (or whenever it was) I have since added leap year functionality to the "long hand" version. You can see it here: http://www.perlskripts.com/cgi-bin/showscript.cgi?dateCalc=

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I've just discovered very important differences between Windows an Unix formats in Perl,at least 5.xx.. MOST IMPORTANT: Use Unix file format while saving Your script. otherwise it will have ^M s or smth likely weird in the EOL, Then DO NOT use m…
There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Six Sigma Control Plans
Suggested Courses

578 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question