KramerC

Converting DateTime.Ticks into a Unix timestamp in PHP

November 30, 2010 at 11:46 AM PST

I needed a way to convert the number of ticks from the DateTime.Ticks property in .NET into a Unix timestamp in PHP. So I wrote up this solution that makes this possible. The solution works by taking the number of ticks that I want to convert into a Unix timestamp and subtracting it with the number of ticks of the Unix epoch.

To figure out the number of ticks of the Unix epoch, I used C# (it is possible to do this in a different .NET language) using these two lines of code to find the number of ticks of the Unix epoch in a simple Console Application:

DateTime unix = new DateTime(1970, 1, 1, 0, 0, 0);
System.Console.WriteLine(unix.Ticks);

This ends up printing out: 621355968000000000

I then took this number, which is in one hundred nanoseconds, and created a PHP function which subtracts the number of ticks to be converted by the number of ticks of the Unix epoch and then divides it by 10000000 to convert the now Unix timestamp from one hundred nanoseconds to seconds as Unix timestamps in PHP are handled in seconds.

<?php
function ticks_to_time($ticks) {
    return floor(($ticks - 621355968000000000) / 10000000);
}
?>

This is an example of this function in use:

<?php
// 11/24/2010 9:20:45 PM UTC in DateTime.Ticks
$time = ticks_to_time(634262304450000000);
echo "$time\n";
echo date("F j Y g:i:s A T", $time) . "\n";
?>

Which should output:

1290633645
November 24 2010 1:20:45 PM PST

So there we have it, a function that makes it easy to convert the number of ticks from the DateTime.Ticks property in .NET into a Unix timestamp in PHP.