Solved

add date in perl

Posted on 2004-09-18
11
6,323 Views
Last Modified: 2008-01-09
please tell me how to add date in perl.
sample : 01/01/2004+14 => 14/01/2004
0
Comment
Question by:divt
  • 3
  • 3
  • 2
  • +2
11 Comments
 
LVL 36

Expert Comment

by:Zyloch
ID: 12090966
Hi divt,

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

Regards,
Zyloch
0
 
LVL 36

Expert Comment

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

Regards...
0
 
LVL 48

Expert Comment

by:Tintin
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.
0
 
LVL 84

Assisted Solution

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

Author Comment

by:divt
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";

exit;

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 ?
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 4

Author Comment

by:divt
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

0
 
LVL 5

Accepted Solution

by:
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.
0
 
LVL 4

Author Comment

by:divt
ID: 12094732
ZiaTioN,

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)

http://www.experts-exchange.com/Programming/Programming_Languages/Perl/Q_21136585.html
0
 
LVL 5

Expert Comment

by:ZiaTioN
ID: 12097359
divt,

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.
0
 
LVL 48

Expert Comment

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

#!/usr/bin/perl
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);
0
 
LVL 5

Expert Comment

by:ZiaTioN
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=
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

On Microsoft Windows, if  when you click or type the name of a .pl file, you get an error "is not recognized as an internal or external command, operable program or batch file", then this means you do not have the .pl file extension associated with …
A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (http://www.mongodb.org/downloads),  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
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…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

706 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now