convert standard timestampt to epoch format using awk/nawk on Solaris

432 Views Asked by At

I need to convert some timestamp on Solaris to epoch format without any GNU installed.

I gave it a try with below code. However, sometime the return value has 1-2 days deviated from the correct value

echo "Mar 20 20:09" | nawk -v FS="[: ]+" 'BEGIN {
    month_array["Jan"]="01";
    month_array["Feb"]="02";
    month_array["Mar"]="03";
    month_array["Apr"]="04";
    month_array["May"]="05";
    month_array["Jun"]="06";
    month_array["Jul"]="07";
    month_array["Aug"]="08";
    month_array["Sep"]="09";
    month_array["Oct"]="10";
    month_array["Nov"]="11";
    month_array["Dec"]="12";
}
{
    year=2016;
    month=month_array[$1];
    day=$2; hour=$3; minute=$4;
    if (month > 2) {
        month=month+1;
    } else {
        month=month+13; year=year-1;
    }

    day=(year*365)+(year/4)-(year/100)+(year/400)+(month*306001/10000)+day;
    days_since_epoch=day-719591;
    seconds_since_epoch=(days_since_epoch*86400)+(hour*3600)+(minute*60);
    printf "%d\n", seconds_since_epoch;
}'
1458677340

bash-3.2$ ctime 1458677340
Tue Mar 22 20:09:00 2016

Thanks so much

1

There are 1 best solutions below

2
jlliagre On

Assuming all month have 30.6 days is obviously doomed.

Here are two ways to do what you want to achieve under Solaris.

Using touch and truss (for the fun):

$ touch -t "03202009" file
$ truss -f -v 'lstat,lstat64' ls -d file 2>&1 | nawk '/mt =/ {printf "%d\n",$10}'
1458504540
$ ctime 1458504540
2016/03/20, 20:09:00

Using perl:

$ touch -t "03202009" file
$ perl -sle '@stat=stat($filename); print "$stat[8]"' -- -filename=file
1458504540