Drop down list of dates

Posted: 22 September 2009 in Javascript, Perl

I had a requirement to let a user choose a date n months from now, as part of a piece of work for content expiry notification.

I had to do it in Perl and I had to do it in JAvascript. Here’s the code I had for Javascript:

var today = new Date();
for (var month=1; month<=12; month++){
    var newDate = new Date(today.getTime());
    newDate.setMonth(newDate.getMonth() + month);
    var newDateString=leadingZero(newDate.getDate()) + "/" + leadingZero(newDate.getMonth()) + "/" + leadingZero(newDate.getFullYear());
function leadingZero(n) {
    return (n != null && n < 10 && n >= 0 ? "0" : "") + n;

and here’s the one in Perl:

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
my $monthsDropDownListOptions  ="";
for (my $month=1; $month<=12; $month++){
    my $selected="";
    if ($month == 6){
        $selected=" selected=\"true\"";

    my $newDate;
    #                   0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11
    my @days_in_month=(31,28,31,30,31,30,31,31,30,31,30,31);
    my $newDateMDays=$mday;
    my $newDateMonth=$mon+$month+1;
    my $newDateYear=$year+1900; # by default, the new date is the same year as today, y2k style
    if ($newDateMonth>12){      # unless the months roll over the year
    # we just need to check that there are sufficient days in the month (e.g. if we're the 31st of Jan and add 1 month, 31st of Feb does not exist
    if ($mday > $days_in_month[$newDateMonth-1]){
    my $newDateString = sprintf("%02d",$newDateMDays) . "/" . sprintf("%02d",$newDateMonth) . "/" . sprintf("%02d",$newDateYear);
    $monthsDropDownListOptions .= qq?<option value="$month"$selected>$newExpiryDateString</option>?;

If you look closely, it does not deal with leap years, but it’s something that can be added if need be. Personnaly, I think one day every for years is not worth the effort 🙂


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s