Connecting Tech Pros Worldwide Help | Site Map

Date Manipulation

Member
 
Join Date: Sep 2008
Posts: 35
#1: Aug 4 '09
Is there a way of getting the previous date when we enter a specific date?

e.g if we enter ... 20090804, it should return 20090803, or even if we enter a future date...20090910, it should return 20090909.
KevinADC's Avatar
Expert
 
Join Date: Jan 2007
Location: Southern California USA
Posts: 4,091
#2: Aug 4 '09

re: Date Manipulation


Quote:

Originally Posted by joeferns79 View Post

Is there a way of getting the previous date when we enter a specific date?

e.g if we enter ... 20090804, it should return 20090803, or even if we enter a future date...20090910, it should return 20090909.

You can use one of the Date modules listed on CPAN or you can write your own code to split the date into tokens (year, month, day) and feed them to Time::Local ( that comes with perl) to convert them into epoch seconds and subtract 24 hours of seconds from the epoch time.
Proof of concept:

Expand|Select|Wrap|Line Numbers
  1. use Time::Local;
  2.  
  3. my $date = '20090910';
  4. my ($y,$m,$d) = unpack("A4A2A2",$date);
  5. my $epoch = timelocal(0,0,0, $d, $m-1, $y) - (60*60*24);
  6. print scalar localtime($epoch);
  7.  
assumes the date is always in YYYYMMDD format, if not you will have to change unpack() to a regexp and do some checking. You can use POSIX to reformat $epoch back into YYYYMMDD. I leave that part up to you. Or as mentioned, look into a Date module.
Member
 
Join Date: Sep 2008
Posts: 35
#3: Aug 5 '09

re: Date Manipulation


Thanks a lot, that worked.
Reply