Introduction #
The Linux shell script below will convert a date, entered on the command line, to an epoch date.
#!/usr/bin/env sh
convert_to_epoch() {
local date_time="$1"
local epoch_time
# GNU/Linux syntax
epoch_time=$(date -d "$date_time" +%s 2>/dev/null)
# Check if the conversion was successful
if [ $? -eq 0 ]; then
echo "Epoch time for '$date_time' is: $epoch_time"
else
echo "Error: Invalid date and time format. Please use a valid format like 'YYYY-MM-DD HH:MM:SS'."
fi
}
if [ $# -eq 0 ]; then
echo "Usage: $0 'YYYY-MM-DD HH:MM:SS'"
echo "Example: $0 '2023-10-01 12:00:00'"
else
oldIFS="$IFS"
IFS=' '
arguments="$*"
t=$(echo $arguments)
convert_to_epoch "$t"
IFS="$oldIFS"
fi