How to convert DATE to UNIX TIMESTAMP into a shell script on MacOS

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

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

Since Mac OS does not have the -d equivalent for a date . How are you going to convert the date to a unix timestamp in a shell script.

+72
date linux shell macos
Sep 28 '10 at 23:26
source share
5 answers

man date on OSX there is this example

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

What 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 any format you want.

+31
Sep 28 '10 at 23:38
source share
 date +%s 

This works great for me on OS X Lion.

+130
Feb 18 2018-12-18T00:
source share

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

+15
Sep 28 '10 at 23:43
source share

On Mac OSX, I used the following.

 currDate=`date +%Y%m%d` epochDate=$(date -j -f "%Y%m%d" "${currDate}" "+%s") 
+2
May 15, '14 at 21:25
source share

Alternatively, you can set the GNU date as follows:

  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 comments that the Mac should be β€œdifferent” simply show that the commenter does not know the history of UNIX. macOS is based on BSD UNIX, which is much older than Linux. In fact, Linux was a copy of other UNIX systems, and Linux decided to become "different" by adopting GNU tools instead of BSD tools. GNU tools are more convenient for the user, but usually they are not found in any * BSD system (just like that).

Indeed, if you spend most of your time on Linux, but you have a Mac desktop, you probably want the Mac to work as Linux. It makes no sense to try to remember two different sets of parameters or scripts for the Mac Bash version of the BSD if you are not writing a utility that you want to run for both BSD shells and GNU / Linux.

+1
Jan 18 '19 at 19:05
source share



All Articles