Php将ldap YMD时间戳转换为适当的日期格式

时间:2015-05-11 11:26:16

标签: php ldap

这些天我学习php。我有一个小任务将ldap YMD时间戳转换为适当的日期格式。

我使用下面的代码来进行conevert,但逻辑似乎是错误的。这是代码:

<?php
function convertLdapTimeStamp($timestamp){
        //PHP script to convert a timestamp returned from an LDAP query into a Unix timestamp 
        // The date as returned by LDAP in format yyyymmddhhmmsst
        $date = $timestamp;

        // Get the individual date segments by splitting up the LDAP date
        $year = substr($date,0,4);
        $month = substr($date,4,2);
        $day = substr($date,6,2);
        $hour = substr($date,8,2);
        $minute = substr($date,10,2);
        $second = substr($date,12,2);

        // Make the Unix timestamp from the individual parts
        $timestamp = mktime($hour, $minute, $second, $month, $day, $year);

        // Output the finished timestamp
        return $month."/".$day."/".$year." ".$hour.":".$minute.":".$second;
    }


convertLdapTimeStamp(20190630175050Z);

?>

输入:'20190630175050Z',输出应为:2017年6月30日晚上11:20:50 IST。

请告诉我如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

我知道这个问题已经老了......但是! 您的代码似乎对我来说很好,这是我现在使用的函数(基于您的)默认日期格式:

function ldap_dt($date, $format = 'd.m.Y H:i:s') {

    // Get the individual date segments by splitting up the LDAP date
    $y = substr($date,0,4);
    $m = substr($date,4,2);
    $d = substr($date,6,2);
    $h = substr($date,8,2);
    $i = substr($date,10,2);
    $s = substr($date,12,2);

    // Make the Unix timestamp from the individual parts
    $timestamp = mktime($h, $i, $s, $m, $d, $y);

    // Output the 'never' for 01.01.1970 01:00, 30.11.1999 00:00, or after now
    if($timestamp == 0 || $timestamp == 943916400 || $timestamp > time())
        return 'never';

    // Output the finished timestamp
    return date($format, $timestamp);
}

使用示例:

echo ldap_dt($date);                   // default date format defined in function
echo ldap_dt($date, 'm/d/Y H:i:s');    // custom date format

答案 1 :(得分:0)

更新

要从非字符串转换为字符串:

ARRONDI

更新结束

这有效并经过测试。

测试代码:

$date = settype($timestamp,'string');

结果:

$time = strtotime('20190630175050Z');  convert string to time
echo date('d M, Y H:i:s A T',$time);