Convert date time string to epoch in Bash Convert date time string to epoch in Bash shell shell

Convert date time string to epoch in Bash


What you're looking for is date --date='06/12/2012 07:21:22' +"%s". Keep in mind that this assumes you're using GNU coreutils, as both --date and the %s format string are GNU extensions. POSIX doesn't specify either of those, so there is no portable way of making such conversion even on POSIX compliant systems.

Consult the appropriate manual page for other versions of date.

Note: bash --date and -d option expects the date in US or ISO8601 format, i.e. mm/dd/yyyy or yyyy-mm-dd, not in UK, EU, or any other format.


For Linux, run this command:

date -d '06/12/2012 07:21:22' +"%s"

For macOS, run this command:

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


A lot of these answers overly complicated and also missing how to use variables. This is how you would do it more simply on standard Linux system (as previously mentioned the date command would have to be adjusted for Mac Users) :

Sample script:

#!/bin/bashorig="Apr 28 07:50:01"epoch=$(date -d "${orig}" +"%s")epoch_to_date=$(date -d @$epoch +%Y%m%d_%H%M%S)    echo "RESULTS:"echo "original = $orig"echo "epoch conv = $epoch"echo "epoch to human readable time stamp = $epoch_to_date"

Results in :

RESULTS:original = Apr 28 07:50:01epoch conv = 1524916201 epoch to human readable time stamp = 20180428_075001

Or as a function :

# -- Converts from human to epoch or epoch to human, specifically "Apr 28 07:50:01" human.#    typeset now=$(date +"%s")#    typeset now_human_date=$(convert_cron_time "human" "$now")function convert_cron_time() {    case "${1,,}" in        epoch)            # human to epoch (eg. "Apr 28 07:50:01" to 1524916201)            echo $(date -d "${2}" +"%s")            ;;        human)            # epoch to human (eg. 1524916201 to "Apr 28 07:50:01")            echo $(date -d "@${2}" +"%b %d %H:%M:%S")            ;;    esac}