How to convert DATE to UNIX TIMESTAMP in shell scr

2019-03-07 22:43发布

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.

5条回答
老娘就宠你
2楼-- · 2019-03-07 23:22

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

The Mac is "different" because OSX is based on BSD. BSD utilities tend to be conservatively updated, while GNU tools have more enhancements.

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. Also see: Docker. There's no sense in trying to remember two different sets of options.

查看更多
做自己的国王
3楼-- · 2019-03-07 23:23

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.

查看更多
萌系小妹纸
4楼-- · 2019-03-07 23:35

I used the following on Mac OSX.

currDate=`date +%Y%m%d`
epochDate=$(date -j -f "%Y%m%d" "${currDate}" "+%s")
查看更多
戒情不戒烟
5楼-- · 2019-03-07 23:36
date +%s

This works fine for me on OS X Lion.

查看更多
疯言疯语
6楼-- · 2019-03-07 23:41

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

查看更多
登录 后发表回答