How to get Time since Epoch in Linux, Mac, Bash

Reading Time: 2 minutes

We will sometime choose to use time since Epoch in command script for cronjob or bash process to simplify interpretation of time throughout the code logic. Hence, let’s go through the methods available to get the time.

To understand more about Epoch, we have an article with more description here.

Ways to retrieve Time since Epoch

  • Current Date & Time
  • Indicating specific Date & Time

Current Date & Time since Epoch

To retrieve the current time in seconds, millisecond and microsecond, below are the illustration on Linux and MacOS.

Do note that due to MacOS limitation, the only way to get millisecond and microsecond is by appending zeros to date +%s result.

# Get current time since Epoch Time (Linux and Mac)

# Retrieve in seconds (Linux and Mac)
$ date +%s     # 1650251652

# Retrieve in milliseconds (Linux)
$ date +%s%3N  # 1650251652139

# Retrieve in microseconds (Linux)
$ date +%s%3N  # 1650251652139837

# Retrieve in nanoseconds (Linux)
$ date +%s%N   # 1650251652139837718

Below show the illustration by using built-in Bash variable where we can easily retrieve it. The advantage is that there is no need for conversion since any conversion would have already done by bash natively.

More description on all available Bash variable here.

# Get current time since Epoch Time (Bash)

# Retrieve in seconds
$ echo $EPOCHSECONDS    # 1650252502

# Retrieve in fractional seconds
$ echo $EPOCHREALTIME   # 1650252502.512864

# Retrieve in millisecond seconds
$ echo $(( ${EPOCHREALTIME/./} / 1000 ))  # 1650252502512

# Retrieve in microsecond seconds
$ echo $(( ${EPOCHREALTIME/./} ))         # 1650252502512864

Indicating specific Date & Time

If we want to use a past or future date, we can pass in the dates in via the below commands. We will only be using date object since it provides the options to format the results by default or with options.

# Get specific time since Epoch Time

# Retrieve in seconds (Linux and Bash)
$ date -d "Apr 18 2022" +%s    # 1650240000
$ date --date @1650240000      # Mon 18 Apr 2022 12:00:00 AM UTC

# Retrieve in seconds (Mac)
$ date -j -f "%b %d %Y %T" "Apr 18 2022 00:00:00" "+%s"  # 1650211200
$ date -j -r 1650211200  # Mon Apr 18 00:00:00 +08 2022


Different system comes with different method to get time since Epoch but they are all very straight forward to use.

Show Comments

No Responses Yet

Leave a Reply