// Internet Duct Tape

Perl Oneliner for date calculation

Posted in Asides, Perl, Technology by engtech on July 27, 2006

Perl is great for writing oneliner scripts to do simple task. I’m often confounded that there are no inherent unix utilities for doing date arithmetic / calculations, since so many unix utilities require the date as an option. Thanks to the Perl Date::Calc module, that isn’t an issue.

Here’s a one liner to find out what the date was 28 days (4 weeks) ago:

perl -e 'use Date::Calc qw(Today Add_Delta_Days); my ($y, $m, $d) = Add_Delta_Days(Today(), -28); print "$y/$m/$d\n";'

Note the value of -28 to tell it to subtract 28 days from the current date. Because it is using Date::Calc, it will correctly handle holidays, different months, leap years, etc (as opposed simply subtracting one from the month which will net you something between 28-31 days).

Note the sexy ISO-8601 return value.

6 Responses

Subscribe to comments with RSS.

  1. shamim said, on August 24, 2006 at 1:44 pm

    Dear Programmer

    I could not run perl one liner program. I am writing
    perl -e ‘print “hello.\n”;’ on the command line. but showing can’t find string terminator. how can i run one liner program in windows. should i download any file to run it? pls inform me.


  2. engtech said, on August 24, 2006 at 5:46 pm

    That one-liner worked for me when I typed it in on Linux.

    What operating system are you running?

    Please cut-n-paste EXACTLY what you typed and the response you get back.


  3. ramlion said, on January 17, 2007 at 6:58 pm

    Hi, I have a need of perl code to input a value in days (nearest whole number) from now (=accessed localtime) to then (march 24 2007)when entering a form page. This is for a charity website doing an auction.

    If you cant help, where might I find a solution.

    Current line reads as follows:-

    Giving a fixed value of 14


  4. engtech said, on January 17, 2007 at 7:52 pm

    I think you want the Date::Calc module.


    I think you’d want to use the Delta_Days function.

  5. Sriram said, on March 02, 2007 at 5:39 pm

    What I need is :

    ” let’s say the logs files are available for Jan 07, Dec 06, Nov 06, Oct 06

    the script should identify the latest months logs, i.e Jan 07

    it should then delete anything older than 2 months from Jan 2007 , which will be logs for Nov 06 & Oct 06.”

    I am working on the below script, but this deletes all files other than the latest date files

    Keepdate=`/bin/ls -ult –full-time| sed 1d | head -1 | awk ‘{ print $6 }’`

    /bin/ls -ltr | grep -v “$Keepdate” | awk ‘{print $NF}’ | xargs -i rm -rf {}

    I need to keep files for X days from latest date (not just one day)

    Can you suggest ?

  6. engtech said, on March 02, 2007 at 8:27 pm

    Hi Sriram,

    I’d love to help but I have no time right now and I’m not familiar with bash scripts (I always use perl instead).

Comments are closed.

%d bloggers like this: