Unix timestamps are extremely useful and can be used across my different programming languages and platforms. I will outline a couple programming languages that support timestamps.
- PHP – convert timestamps to date in php
- MysQL – view example on how you can query timestamps from a MySQL Database
- Perl – the time() function in Perl can handle unix timestamps
- Linux – return current timestamp in linux
Real World Unix Timestamp Examples
In PHP, you can convert a unix timestamp to a real time by using the php date() function. date() allows you to convert a timestamp that is supplied as the second parameter or if the second parameter is left out, it will convert the current timestamp to date.
<?php /* this would display a time of 23 May 2011 17:12:pm */ echo date('d F Y H:i:a',1306134726); /* and this would display the current time in the same format as above */ echo date('d F Y H:i:a'); ?>
The way the date is displayed is controlled by the flags passed to the function. Here we used the flags ‘d’, ‘F’, ‘Y’, ‘H’, ‘i’ and ‘A’. For a complete list of flags and to see a complete description of this function, visit http://php.net/manual/en/function.date.php.
The PHP function time(), strtotime() and mktime() all return the current unix timestamp. If you wanted to, you can also get a time stamp 24 hours from now by using the following code.
<?php /* get tomorrows timestamp */ $tomorrow = time() + (24 * 60 * 60); /* or you can use strtotime to convert a natural string into a timestamp */ $tomorrow = strtotime('+24 hours'); /* and this will create a timestamp based on the date and time variables */ $timestamp = mktime($hour,$min,$sec,$month,$day,$year); ?>
If you have a table that contains a column with a unix timestamp in it, you can convert it using the query below. It will return a column that contains rows of easy to read date and times.
SELECT FROM_UNIXTIME(column_name) AS real_time FROM `table_name`;
In order to retrieve the current timestamp in Perl, you can make use of the time() function which is the same as PHP.
my $timestamp = time();
Using the ‘date’ command in linux will print out the date specified by the parameters passed to it. We will use the %s flag to tell it to print the seconds passed since ‘1970-01-01 00:00:00 UTC’ (i.e. it will print out the current timestamp).