How to convert an “epoch”-time to a meaningful date and time

Most, if not all *NIX-based systems store time and date values as epoch, means in seconds after a certain date, usually the seconds passed since 00:00:00 UTC Jan 1, 1970. Not a perfect approach, but sufficently accurate for most purposes. If you are confronted with such a value, then there are a couple of apporaches to convert it to something meaningful. The easiest way (again, on *NIX-based systems) is the following command:

date -r epoch_seconds

it returns a date-string readable by humans (and other beings familiar with the time-system used on earth). An example says more than any complicated explanation:

$ perl -e 'print time."\n";'
$ date -r 1157445071
Tue Sep 5 10:31:11 CEST 2006

BTW: The perl-comand shown above comes handy if you need to know the current time in epoch-seconds.

But, the fun doesn’t stop here. Recently I had to convert epoch-times and do some calculations with it. Lazy as I am (you already got that, didn’t you), I decided to use AppleScript to do the calculations, but since I could not find an AppleScript-function capable of converting epoch-seconds, I used its capabilities to access the *NIX-brain beneath the pretty GUI. Without further ado, here is a handler to do the calculation:

on epoch2datetime(epochseconds)
	set myshell1 to "date -r "
	set myshell2 to " \"+%m/%d/%Y %H:%M\""

	set theDatetime to do shell script (myshell1 & epochseconds & myshell2)

	return date theDatetime
end epoch2datetime

The return-value is fit to be fed into an AppleScript-command which converts it into a date-time value AppleScript can work with.

Hope this helps. 😀 BTW: I’ll try to figure out how to color the AppleScript later. Be careful if you do a copy and paste with the code shown, WordPress insists on messing up the quotes, sorry.

Technorati Tags: , , ,

One Trackback

  1. […] für ein Script Unix-Zeitstempel in ein Apple-Script-Datum konvertieren, und fand bei einer Suche diesen QuelleCode, der anscheinend nur unter englischen System funktioniert…. Nun, deshalb habe ich mir meine […]