Convert a given time to seconds in solaris
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:581367223478
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
In C/C++ on UNIX, you can convert directly:
struct tm tm;time_t t;tm.tm_isdst = -1;if (strptime("2013-04-29 08:17:58", "%Y-%m-%d %H:%M:%S", &tm) != NULL) { t = mktime(tm);}cout << "seconds since epoch: " << t;
See Opengroup manpage strptime()
for the example.
I admire the strace/touch niftyness and the creativity behind it. Though, well, just don't do this in a tight loop ...