Search code examples
macosdateepochbsd

Sends from epoch, for 1 year ago on MacOS / BSD?


I'm trying to calculate the number of seconds since the Epoch, using date on MacOS BSD.

I can get a one year ago date string:

$ date -v -1y

Tue Apr 21 10:44:47 EST 2020

...but I can't figure out how to convert it into seconds since Epoch. Any suggestions?


Solution

  • Add +%s to tell it to print the datetime as seconds since the epoch:

    date -v -1y +%s
    

    The + is a date option to set the output format, and %s is strftime format for "seconds since epoch".

    Portability note: while the +%s part is pretty standard and portable (though the %s format is not actually required by POSIX), the -v -1y part is wildly nonportable. With GNU date (e.g. on most Linuxes), you'd use something like --date='1 year ago' instead. On NetBSD, -d '1 year ago' works. Check your local man page to see what your system supports.