88 users online (0 members and 88 guests)

# Thread: Find a date string of previous months

Results 1 to 2 of 2
1. ## Find a date string of previous months

Hello all,

I need to find out a date string of previous months. I have a loop that goes back n amount of months and I need to get following list:

2005-08
2005-07
2005-06
2005-05
2005-04
2005-03
2005-02
etc...

How do I do it? Currently I have this formula to get month string of a a months ago, but it gets messy when a certain month has less the 31 days etc...

sub getNewMonth
{
# Subtract given months from today's month
my \$months = \$_[0];

my \$rightnow = time();
\$rightnow -= (3600 * 24 * 31 * \$months);

# Get subtracted date
my (\$sec,\$min,\$hr,\$mday,\$mon,\$year,\$wday,\$yday,\$isdst) = localtime(\$rightnow);
\$year = \$year + 1900;
\$mon++;

my \$newdate = "\$year-\$mon";

return \$newdate;
}

2. ## Re: Find a date string of previous months

try this insted:
Code:
```sub getNewMonth
{
@daysinmonths = ("31", "28", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31");
# Subtract given months from today's month
my \$months = \$_[0];
#there is one problem in these lines of code... \$year needs to be the current year
#if(\$months == 1 && (\$year % 4) == 0){
#\$months[1] = 29;
#}
my \$rightnow = time();
\$rightnow -= (3600 * 24 * \$daysinmonths[\$months] * \$months);

# Get subtracted date
my (\$sec,\$min,\$hr,\$mday,\$mon,\$year,\$wday,\$yday,\$isdst) = localtime(\$rightnow);
\$year = \$year + 1900;
\$mon++;

my \$newdate = "\$year-\$mon";

return \$newdate;
}```