简体   繁体   中英

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

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 have the equivalent -d for date . How do you go about converting a date to a unix timestamp in a shell script.

date +%s

这在 OS X Lion 上对我来说很好用。

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.

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

I used the following on Mac OSX.

currDate=`date +%Y%m%d`
epochDate=$(date -j -f "%Y%m%d" "${currDate}" "+%s")

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.

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

当没有%H:%M:%S00:00:00时,它将打印动态00:00:00

I wrote a set of scripts that provides a uniform interface for both BSD and GNU version of date .

Follow command will output the Epoch seconds for the date 2010-10-02 , and it works with both BSD and GNU version of date .

$ xsh /date/convert "2010-10-02" "+%s"
1286020263

It's an equivalent of the command with GNU version of date :

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

and also the command with BSD version of date :

date -j -f "%F" 2010-10-02 "+%s"

The scripts can be found at:

It's a part of a library called xsh-lib/core . To use them you need both repos xsh and xsh-lib/core , I list them below:

要将 UTC 中的日期转换为 Unix 时间戳:

date -ju -f "%F %T" "2021-03-08 14:56:21" "+%s"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM