Search code examples
bashdatetimebsd

Create a bash date/time variable from argument


Given an argument being passed in like this:

~/Documents/checkout/check-out.sh potatoes '2013/05/22 13:43:00'

Using 1st or 2nd line, produces

st=`date --date "$2" +%s`                   # mogul's suggestion
st=$(date --date="$2" +%s)                  # Kent's suggestion
st=$(date --date="2013/05/22 14:45:00" +%s)

date: illegal option -- -
usage: date [-jnu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... 
    [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]

Solution

  • OS X's version of date doesn't understand the --date option; you need to use -f and give it the format of the input date:

    st=$(date -j -f "%Y/%m/%d %T" "$2" +%s)
    

    For example:

    $ date -j -f "%Y/%m/%d %T" "2013/05/22 14:45:00" +%s
    1369259100