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
Tunneling With SSH to Your Destination
Viewed 4208 times since Wed, May 30, 2018
How to sort IP addresses in Linux
Viewed 3793 times since Thu, May 24, 2018
Transform XML to CSV Format | Unix String Pattern Manipulation The Ugly Way
Viewed 5197 times since Sun, Jan 9, 2022
30 Examples for Awk Command in Text Processing
Viewed 14685 times since Sat, Nov 24, 2018
perl podstawy
Viewed 1980 times since Mon, May 21, 2018
10 Xargs Command Examples in Linux / UNIX
Viewed 3803 times since Fri, Jun 1, 2018
Using Shell Redirection: All About the Here-Doc
Viewed 10248 times since Wed, May 30, 2018
Convert a human readable date to epoch with a shell script on OpenBSD and Mac OS X
Viewed 14977 times since Fri, May 25, 2018
The Ultimate Bash Array Tutorial with 15 Examples
Viewed 13189 times since Sun, Sep 30, 2018
Script HW/SW AIX
Viewed 9065 times since Mon, Jun 4, 2018