add date in perl

Posted on 2004-09-18
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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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.
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 84

Assisted Solution

ozo earned 20 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:

From date 01/01/2004 , wait 14 days before 15/01/2004


Accepted Solution

ZiaTioN earned 230 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:

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

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

Suggested Solutions

Title # Comments Views Activity
Uploading Binary Data using Perl 5 99
Shell script to bind my job to half the number of vCPUs in Solaris 8 123
Awk Question 2 132
Perl tar error 8 69
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…
In the distant past (last year) I hacked together a little toy that would allow a couple of Manager types to query, preview, and extract data from a number of MongoDB instances, to their tool of choice: Excel (…
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…

749 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