`date` command on OS X doesn't have ISO 8601 `-I` option?

后端 未结 9 1508

In a Bash script, I want to print the current datetime in ISO 8601 format (preferably UTC), and it seems that this should be as simple as date -I:

http://ss

相关标签:
9条回答
  • 2021-01-29 19:50

    A short alternative that works on both GNU and BSD date is:

    date -u +%FT%T%z
    
    0 讨论(0)
  • 2021-01-29 19:50

    I regularly use 'date -I' in Linux when saving files. ex: touch x.date -I. While the equivalent in MacOS is 'date +%F', it is a bit awkward to type every time I save a file. So, I set an alias "alias dt='date +%F'" then touch x.dt gives me the date.

    0 讨论(0)
  • 2021-01-29 19:51

    Just use normal date formatting options:

    date '+%Y-%m-%d'
    

    Edit: to include time and UTC, these are equivalent:

    date -u -Iseconds
    
    date -u '+%Y-%m-%dT%k:%M:%S%z'
    
    0 讨论(0)
  • 2021-01-29 19:51

    It's not a feature of Bash, it's a feature of the date binary. On Linux you would typically have the GNU coreutils version of date, whereas on OSX you would have the BSD legacy utilities. The GNU version can certainly be installed as an optional package, or you can roll your own replacement - I believe it should be a simple one-liner e.g. in Perl.

    0 讨论(0)
  • 2021-01-29 20:01

    Taking the other answers one step further, you could add a function to your ~/.bashrc or ~/.zshrc to add the date -I flag:

    date() {
      if [ "$1" = "-I" ]; then
        command date "+%Y-%m-%dT%H:%M:%S%z"
      else
      command date "$@"
      fi
    }
    
    0 讨论(0)
  • 2021-01-29 20:02

    There's a precompiled coreutils package for Mac OS X available at:

    http://rudix.org/packages-abc.html#coreutils.

    0 讨论(0)
提交回复
热议问题