Search code examples
linuxbashunix-timestamp

Round date math to nearest month while calculating UNIX time


I want to acquire the UNIX timestamp value (seconds since January 1st 1970) for an offset from the present, while rounding the result to the beginning of the month.

Essentially I want this output -- two months from current date, but the first day of that month.

date -d "2019-04-01" "+%s"
1554102000

However I don't want to manually add the date. I want to do something similar to this:

date -d +"%Y%m" --date="+2 month" +"%s"
1555973219

but unfortunately this gives me the incorrect timestamp (the result is not rounded to the beginning of the month).


Solution

  • Demonstrating that this all works correctly when using GNU date:

    set -x
    date
    start_of_2mo_hence=$(date -d 'now + 2 months' +%Y-%m-01)
    start_of_2mo_hence_sec=$(date -d "$start_of_2mo_hence" +%s)
    date -d "@$start_of_2mo_hence_sec"
    

    ...emits:

    + date
    Fri Feb 22 17:04:49 CST 2019
    ++ date -d 'now + 2 months' +%Y-%m-01
    + start_of_2mo_hence=2019-04-01
    ++ date -d 2019-04-01 +%s
    + start_of_2mo_hence_sec=1554094800
    + date -d @1554094800
    Mon Apr  1 00:00:00 CDT 2019
    

    Of course, this could be simplified to:

    start_of_2mo_hence_sec=$(date -d "$(date -d 'now + 2 months' +%Y-%m-01)" +%s)