Convert a human readable date to epoch with a shell script on OpenBSD and Mac OS X

Convert a human readable date to epoch with a shell script on OpenBSD and Mac OS X

Dates can be quite challenging. Especially if you systematically want to use dates, for example to compare what date is older.

If you would like to convert this date into epoch, take these steps.

$ # The first step is to print the date.
$ echo "2009/05/25 18:34:30;"
2009/05/25 18:34:30;
$ # This step is to strip the /-es.
$ echo "2009/05/25 18:34:30;" | sed 's%/%%g'
20090525 18:34:30;
$ # This step removes the space
$ echo "2009/05/25 18:34:30;" |  sed 's%/%%g;s% %%g'
2009052518:34:30;
$ # This step removes the trailing :30;.
$ echo "2009/05/25 18:34:30;" | sed 's%/%%g;s% %%g;s%:..;%%'
2009052518:34
$ # This step removes the :.
$ echo "2009/05/25 18:34:30;" | sed 's%/%%g;s% %%g;s%:..;%%;s%:%%g'
200905251834
$ # Finally feed that output to the "date" command.
$ date -j "+%s" $(echo "2009/05/25 18:34:30;" | sed 's%/%%g;s% %%g;s%:..;%%;s%:%%g')
1243269240

 

On Mac OS X you'd have to use this command:

$ date -j -f date -j -f "%Y/%m/%d %T" "2009/10/15 04:58:06" +"%s"
1255575486
5 (1)
Article Rating (1 Votes)
Rate this article
Attachments
There are no attachments for this article.
Comments (1)
Comment By Sayeef - Fri, Jun 4th, 2021 10:50 PM
alias epochtime='a=`date` && date -j -f date -j -f "%a %b %d %T %Z %Y" $a \+\"%s\"'
Full Name
Email Address
Security Code Security Code
Related Articles RSS Feed
O’Reilly’s CD bookshelf
Viewed 15719 times since Wed, Jun 27, 2018
“Yes/No” in Bash Script – Prompt for Confirmation
Viewed 36378 times since Mon, Feb 18, 2019
Linux / UNIX: Convert Epoch Seconds To the Current Time
Viewed 3939 times since Fri, May 25, 2018
Linux and Unix xargs command tutorial with examples
Viewed 4653 times since Fri, Jun 1, 2018
8 Practical Examples of Linux Xargs Command for Beginners
Viewed 6825 times since Fri, Jun 1, 2018
How to get a password from a shell script without echoing - solutions
Viewed 16138 times since Fri, Feb 22, 2019
perl podstawy
Viewed 2658 times since Mon, May 21, 2018
How to sort IP addresses in Linux
Viewed 4777 times since Thu, May 24, 2018
Linux: Repeat Command N Times – Bash FOR Loop
Viewed 4101 times since Mon, Feb 18, 2019
10 Awk Tips, Tricks and Pitfalls
Viewed 6918 times since Wed, Aug 19, 2020