Convert Epoch Time to Standard Date and Time & Vice Versa

Hi guys,

I know that this topic has been discuss numerous times, and I have search the net and this forum for it.

However, non able to address the problem I faced so far.

I am on Solaris Platform and unable to install additional packages like the GNU date and gawk to make use of their functions.

Hence, I intend to go for Perl and include a one-liner command in the shell script for the conversion.

As you can see below, I have no problem converting Epoch to Standard Date/Time.
But for converting Standard Date/Time to Epoch, I am not getting the correct Epoch value.

Am I missing anything here? :confused:

Convert Epoch to Standard Date/Time

bash-3.00# perl -e 'print scalar(localtime(1226424300)), "\n"'
Wed Nov 12 01:25:00 2008

Convert Standard Date/Time to Epoch

bash-3.00# perl -e 'use Time::Local; print timelocal(0,25,1,11,11,2008), "\n";'
1228929900
bash-3.00# perl -e 'use Time::Local; print timegm(0,25,1,11,11,2008), "\n";'
1228958700

Thanks in advance.

works for me:

[yogeshs@helptoldreal-lr yogeshs]$ perl -e 'use Time::Local; print timelocal(0,25,1,11,11,2008), "\n";'
1228938900
[yogeshs@helptoldreal-lr yogeshs]$ perl -e 'print scalar(localtime(1228938900)), "\n"'
Thu Dec 11 01:25:00 2008
[yogeshs@helptoldreal-lr yogeshs]$

can you post a similar example where the epoch value you got is incorrect?

Hi Yogesh,

Thanks for the reply.

I found out that the month parameter for perl timelocal() need to "- 1".
As in Jan to specify "0", Dec to specify 11.
I got the value wrong, thats why epoch is not returning a consistent value.

bash-3.00# perl -e 'print scalar(localtime(1226426701)), "\n"'
Wed Nov 12 02:05:01 2008
bash-3.00# perl -e 'use Time::Local; print timelocal(1,5,2,12,10,2008), "\n"'
1226426701

Really appreciate your help

can i use above function as below .?

i=1226424300;
perl -e 'print scalar(localtime("$i")), "\n"'

Thanks
Avklinux

Thats it. 0-11 for the months just like localtime(). Good catch.

Not sure about perl but in bash:

# epoch
$ date +%s

# If you have a time already in mind you can change the line above to use YOUR time and not system time like this:

date -d "Sat Feb  7 00:37:06 EST 2009" +%s

# result = 1233985026

# and back to regular time from epoch

date --date "Jan 1, 1970 00:00:00 +0000 + `date +%s` seconds"

#You can substitute `date +%s` in the line above with your own epoch time that you have already obtained

date --date "Jan 1, 1970 00:00:00 +0000 + 1233985026 seconds"

# result = Sat Feb 7 00:37:06 EST 2009