Skip to content

Instantly share code, notes, and snippets.

@drewjoh
Created September 26, 2010 00:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drewjoh/597458 to your computer and use it in GitHub Desktop.
Save drewjoh/597458 to your computer and use it in GitHub Desktop.
Ticks to Timestamp Function
<?php
/*
* Ticks To Unix Timestamp
*
* Function to get a usable timestamp from ticks
* Returns a unix timestamp or MySQL datetime
*
* $ticks - the tick (timestamp) that we're converting to a unix timestamp
* $offset - the time offset in hours to adjust the result to
* $return_mysql_date - trigger to return a mysql datetime format or just a unix timestamp
*
* Author: Drew Johnston - http://drewjoh.com
* This code is free and provided as-is. Attribution is appreciated and encouraged.
*/
function ticks_to_timestamp($ticks, $offset = 0, $return_mysql_date = false)
{
// Get the number of ticks for the offset (in hours) - hours*minutes*seconds*ticks
$ticks_to_offset = $offset * 60 * 60 * 10000000;
// This is the number of ticks from 0001-01-01 to 1970-01-01, accounting for leap years
$past_ticks = 621355968000000000;
// Now return our value in the desired format
if($return_mysql_date)
return date('Y-m-d h:i:s', round((($ticks - $past_ticks) + $ticks_to_offset) / 10000000));
else
return round(($ticks - $past_ticks) + $ticks_to_offset) / 10000000;
}
@v9n
Copy link

v9n commented Sep 26, 2010

why not write like this:
return $return_mysql_date? ...
Shorter than much and more clear

@drewjoh
Copy link
Author

drewjoh commented Sep 26, 2010

Hi, can you specify which line you're talking about? The $return_mysql_date is just a trigger (true/false) to know what format to return the result in.

@v9n
Copy link

v9n commented Sep 26, 2010

Just a minor change for shoeter and more clear
return $return_mysql_date)? date('Y-m-d h:i:s', round((($ticks - $past_ticks) + $ticks_to_offset) / 10000000)) : return round(($ticks - $past_ticks) + $ticks_to_offset) / 10000000;

@drewjoh
Copy link
Author

drewjoh commented Sep 26, 2010

Ooh, I gotcha. I agree the ternary operator can make some things shorter and clearer like: echo ($gender = 'male' ? ' selected' : '');

But I personally think with long return statements that are doing calculations like in this function, it's clearer (to me anyway :) to have them on separate lines.

I appreciate the review and feedback!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment