Time conversion using Bash

Time conversion using Bash

 

This article show how you can obtain the UNIX epoch time (number of seconds since 1970-01-01 00:00:00 UTC) using the Linux bash "date" command. It also shows how you can convert a UNIX epoch time to a human readable time.

Obtain UNIX epoch time using bash
Obtaining the UNIX epoch time using bash is easy. Use the build-in date command and instruct it to output the number of seconds since 1970-01-01 00:00:00 UTC. You can do this by passing a format string as parameter to the date command. The format string for UNIX epoch time is '%s'.

lode@srv-debian6:~$ date "+%s"
1234567890

To convert a specific date and time into UNIX epoch time, use the -d parameter. The next example shows how to convert the timestamp "February 20th, 2013 at 08:41:15" into UNIX epoch time.

lode@srv-debian6:~$ date "+%s" -d "02/20/2013 08:41:15"
1361346075

Converting UNIX epoch time to human readable time
Even though I didn't find it in the date manual, it is possible to use the date command to reformat a UNIX epoch time into a human readable time. The syntax is the following:

lode@srv-debian6:~$ date -d @1234567890
Sat Feb 14 00:31:30 CET 2009

The same thing can also be achieved using a bit of perl programming:

lode@srv-debian6:~$ perl -e 'print scalar(localtime(1234567890)), "\n"'
Sat Feb 14 00:31:30 2009

Please note that the printed time is formatted in the timezone in which your Linux system is configured. My system is configured in UTC+2, you can get another output for the same command.

 

date -d @1234567890

echo 1234567890 | awk '{print strftime("%c",$1)}'

0 (0)
Article Rating (No Votes)
Rate this article
Attachments
There are no attachments for this article.
Comments
There are no comments for this article. Be the first to post a comment.
Full Name
Email Address
Security Code Security Code
Related Articles RSS Feed
“Yes/No” in Bash Script – Prompt for Confirmation
Viewed 35829 times since Mon, Feb 18, 2019
Using Shell Redirection: All About the Here-Doc
Viewed 11420 times since Wed, May 30, 2018
awk printf
Viewed 16891 times since Wed, Aug 19, 2020
perl podstawy
Viewed 2532 times since Mon, May 21, 2018
Linux / UNIX: Convert Epoch Seconds To the Current Time
Viewed 3693 times since Fri, May 25, 2018
Tunneling With SSH to Your Destination
Viewed 5524 times since Wed, May 30, 2018
HowTo: Clear BASH History
Viewed 2842 times since Mon, Feb 18, 2019
Utilities to Tidy Up Your Reports
Viewed 16822 times since Wed, May 30, 2018
Script HW/SW AIX
Viewed 10248 times since Mon, Jun 4, 2018
30 Examples for Awk Command in Text Processing
Viewed 16513 times since Sat, Nov 24, 2018