Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a given time to seconds in solaris

I have a time like 2013-04-29 08:17:58. And i need to convert it to seconds since epoch time. No perl please and my OS is solaris. +%s does not work. nawk 'BEGIN{print srand()}' converts the current time to seconds but does not convert a given time to seconds.

Thanks

like image 969
Asish Pati Avatar asked Sep 18 '13 09:09

Asish Pati


1 Answers

Here is a shell function that doesn't require perl:

function d2ts
{
    typeset d=$(echo "$@" | tr -d ':- ' | sed 's/..$/.&/')
    typeset t=$(mktemp) || return -1
    typeset s=$(touch -t $d $t 2>&1) || { rm $t ; return -1 ; }
    [ -n "$s" ] && { rm $t ; return -1 ; }
    truss -f -v 'lstat,lstat64' ls -d $t 2>&1 | nawk '/mt =/ {printf "%d\n",$10}'
    rm $t
}

$ d2ts 2013-04-29 08:17:58           
1367216278

Note that the returned value depends on your timezone.

$ TZ=GMT d2ts 2013-04-29 08:17:58
1367223478

How it works:

  • The first line converts the parameters to a format suitable for touch (here "2013-04-29
  • 08:17:58" -> "201304290817.58" )
  • The second line creates a temporary file
  • The third line change the modification time of the just created file to the required value
  • The fourth line aborts the function if setting the time failed, i.e. if the provided time is invalid
  • The fifth line traces the ls command to get the file modification time and prints it as an integer
  • The sixth line removes the temporary file
like image 57
jlliagre Avatar answered Sep 24 '22 14:09

jlliagre