Convert Windows Timestamp to date using PHP on a Linux Box

徘徊边缘 提交于 2019-12-29 04:24:13

问题


I have an intranet running on a linux box, which authenticates against Active Directory on a Windows box, using LDAP through PHP.

I can retrieve a user's entry from AD using LDAP and access the last login date from the php array eg:

echo $adAccount['lastlogontimestamp'][0]; // returns something like 129802528752492619

If this was a Unix timestamp I would use the following PHP code to convert to a human readable date:

date("d-m-Y H:i:s", $lastlogontimestamp);

However, this does not work. Does anyone know how I can achieve this or indeed if it is possible to do so from a Linux box?


回答1:


According to this, the windows timestamp you have there is the number of 100-ns since Jan 1st 1601. Therefore, you could just convert it to a unix timestamp using the following formula:

tUnix = tWindow/(10*1000*1000)-11644473600;

You divide by 10*1000*1000 to convert to seconds since Jan 1st 1601 and then you discount 11644473600 which is the number of seconds between Jan 1601 and Jan 1970 (unix time).

So in PHP:

date("d-m-Y H:i:s", $lastlogontimestamp/10000000-11644473600);

EDIT: Interestingly, I got a different offset than Baba. I got mine with Java:

Calendar date1 = Calendar.getInstance(); date1.set(1601, 1, 1);
Calendar date2 = Calendar.getInstance(); date2.set(1970, 1, 1);
long dt = date2.getTimeInMillis() - date1.getTimeInMillis();
System.out.println(String.format("%f", dt / 1000.0)); // prints "11644473600.000000"

According to this SO: Ways to Convert Unix/Linux time to Windows time my offset is correct.




回答2:


Since windows is not in seconds but in nano seconds you need to round it up by dividing it by 10000000 you also need to remove seconds between 1601-01-01 and 1970-01-01since windows timestamp start from 1601-01-01

function convertWindowsTimestamp($wintime) {
   return $wintime / 10000000 - 11644477200;
}

$lastlogontimestamp = convertWindowsTimestamp("129802528752492619");
$date = date("d-m-Y H:i:s", $lastlogontimestamp);
var_dump($date);

Output

string '30-04-2012 10:47:55' (length=19)


来源:https://stackoverflow.com/questions/10411954/convert-windows-timestamp-to-date-using-php-on-a-linux-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!