I need a one-line UNIX shel command to add or subtract seconds or hours from a date.

Posted on 2008-11-19
Last Modified: 2013-12-26
I need a one-line command to add or subtract seconds or hours from a date.  I have the pieces but I can't put them together in a one-line command.  I have to build this command on the fly in my EDI mapper so I can't write and execute a regular multi-line script from a .sh file.  It all has to fit on one line and called in one shot.  

Current time = 20081119 14:22

date +%s

And then I can calculate a time 1 hour ago
expr 1227122553 - 3600

and them put it back together as a date in proper format

date -d @1227118953 '+%Y%m%d %H:%M'
20081119 13:22

Now how do I string this into a one-line command to get the date, add/subtract x amount of seconds and then convert back to date format (ie: 20081119 12:21:14)?    

Something like this but this does't work - "date -d @ {expr date+%s - 3600} '+%Y%m%d %H:%M''"

Question by:INAUSA
    LVL 48

    Accepted Solution


    If you simply want the time 1 hour ago, you can do

    date --date '1 hour ago' +'%Y%m%d %H:%M'
    LVL 68

    Expert Comment

    works in ksh:

    date -d @$(($(date  '+%s')-3600)) '+%Y%m%d %H:%M'



    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    This Windows batch file is useful for organizing image files from a digital camera or other source, but can have many other uses.  It simply renames the file(s) to match their create date.  For example, if you took a picture today at 1:40pm and the …
    Background Still having to process all these year-end "csv" files received from all these sources (including Government entities), sometimes we have the need to examine the contents due to data error, etc... As a "Unix" shop, our only readily …
    Learn several ways to interact with files and get file information from the bash shell. ls lists the contents of a directory: Using the -a flag displays hidden files: Using the -l flag formats the output in a long list: The file command gives us mor…
    This video is in connection to the article "The case of a missing mobile phone (". It will help one to understand clearly the steps to track a lost android phone.

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now