I just got done writing a method to compare two dates. The purpose of the function is to return 1 if the first date is greater than the second (further in the future) and 0 otherwise. The two dates are passed to a subroutine in the following format:
[M]M/[D]D/YYYY
The elements within
[] are optional characters. For example, 1/1/2001 would be legal, as would 12/12/2001, but not, 12/12/01. The year requires all four digits.
This is the function I came up with, but I just feel that there must be an easier way to accomplish this task.
sub isGreater
{
my $currDate = $_[0];
my $oldDate = $_[1];
my $currMonth = substr($currDate, 0, index($currDate, "\/"));
$currDate = substr($currDate, index($currDate, "\/")+1);
my $oldMonth = substr($oldDate, 0, index($oldDate, "\/"));
$oldDate = substr($oldDate, index($oldDate, "\/")+1);
my $currDay = substr($currDate, 0, index($currDate, "\/"));
$currDate = substr($currDate, index($currDate, "\/")+1);
my $oldDay = substr($oldDate, 0, index($oldDate, "\/"));
$oldDate = substr($oldDate, index($oldDate, "\/")+1);
my $currYear = $currDate;
my $oldYear = $oldDate;
if ( $currYear > $oldYear )
{
return 1;
}
elsif ( $currMonth > $oldMonth )
{
return 1;
}
elsif ( $currDay > $oldDay )
{
return 1;
}
return 0;
}
As you can see, I'm simply grabbing all the characters up to a "/" and then I go back and cut off the front of the date up to (and including that "/"). Simply put, I grab the month from
$oldDate, store it into
$oldMonth, and then modify
$oldDate to go from MM/DD/YYYY to DD/YYYY. For example, if
$oldDate contained 1/12/2001,
$oldMonth would contain 1 and
$oldDate would contain 12/2001.
This method works fine (as far as I can tell - I'm sure it could use more testing), but is there an easier way to pull this off? I'm not overly familiar with Perl and I wonder if there is a built in function to do something quite similar to what I'm doing here.
Thanks,
- Sherlock
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.