How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

后端 未结 6 686
滥情空心
滥情空心 2021-01-30 02:53

On Linux you can convert a date like \"2010-10-02\" to a unix timestamp in shell script by

date -d \"2010-10-02\" \"+%s\"

Since Mac OS does not

相关标签:
6条回答
  • 2021-01-30 03:21

    Alternatively you can install GNU date like so:

    1. install Homebrew: https://brew.sh/
    2. brew install coreutils
    3. add to your bash_profile: alias date="/usr/local/bin/gdate"
    4. date +%s 1547838127

    Comments saying Mac has to be "different" simply reveal the commenter is ignorant of the history of UNIX. macOS is based on BSD UNIX, which is way older than Linux. Linux essentially was a copy of other UNIX systems, and Linux decided to be "different" by adopting GNU tools instead of BSD tools. GNU tools are more user friendly, but they're not usually found on any *BSD system (just the way it is).

    Really, if you spend most of your time in Linux, but have a Mac desktop, you probably want to make the Mac work like Linux. There's no sense in trying to remember two different sets of options, or scripting for the mac's BSD version of Bash, unless you are writing a utility that you want to run on both BSD and GNU/Linux shells.

    0 讨论(0)
  • 2021-01-30 03:24

    date -j -f "%Y-%m-%d %H:%M:%S" "2020-04-07 00:00:00" "+%s"

    It will print the dynamic seconds when without %H:%M:%S and 00:00:00.

    0 讨论(0)
  • 2021-01-30 03:27

    man date on OSX has this example

    date -j -f "%a %b %d %T %Z %Y" "`date`" "+%s"
    

    Which I think does what you want.

    You can use this for a specific date

    date -j -f "%a %b %d %T %Z %Y" "Tue Sep 28 19:35:15 EDT 2010" "+%s"
    

    Or use whatever format you want.

    0 讨论(0)
  • 2021-01-30 03:27

    I used the following on Mac OSX.

    currDate=`date +%Y%m%d`
    epochDate=$(date -j -f "%Y%m%d" "${currDate}" "+%s")
    
    0 讨论(0)
  • 2021-01-30 03:29
    date +%s
    

    This works fine for me on OS X Lion.

    0 讨论(0)
  • 2021-01-30 03:37

    date -j -f "%Y-%m-%d" "2010-10-02" "+%s"

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