duanliang8464 2014-04-23 13:16
浏览 226
已采纳

SNMP DateAndTime十六进制字符串在PHP中转换为人类日期

When i want to get the cablemodem event log via SNMP, then i snmpwalk the 'mib-2.69.1.5.8.1' oid, but I had the problem because the SNMP store every event date in 'special' hex-string called DateAndTime format.

(In my case this is a 8 byte hex-string, like this: 07 B2 01 01 00 0A 14 00)

I would like to convert to human date, like this (1970.01.01. 00:10), so I wrote a PHP function:

function hex2date( $hexstring ) {
  $date = "";

  $p = unpack( "H*", substr( $hexstring, 0, 2 ) );  // year (2 byte)
  $date .= hexdec( $p[1] ).".";

  $p = unpack( "H*", substr( $hexstring, 2, 1 ) );  // month (1 byte)
  $date .= sprintf( "%02s", hexdec( $p[1] ) ).".";

  $p = unpack( "H*", substr( $hexstring, 3, 1) );   // day (1 byte)
  $date .= sprintf( "%02s", hexdec( $p[1] ) ).". ";

  $p = unpack( "H*", substr( $hexstring, 4, 1 ) );  // hour (1 byte)
  $date .= sprintf( "%02s", hexdec( $p[1] ) ).":";

  $p = unpack( "H*", substr( $hexstring, 5, 1 ) );  // minute (1 byte)
  $date .= sprintf( "%02s", hexdec( $p[1] ) );

  return ($date);
}

This is work, however for some reason I think that this is not the most elegant solution. Am I right?

  • 写回答

1条回答 默认 最新

  • dougang6178 2014-04-23 13:31
    关注

    For travellers from Google, in this case the device sends an 8 byte SNMP DateAndTime value without timezone information. Check the manual I've linked below. However, obtaining the timezone information follows the same principles.


    Your code should look like this:

    // Prepare test data
    $binstring = "\x07\xB2\x01\x01\x00\x0A\x14\x00";
    
    $values = unpack('nyear/Cmonth/Cday/Chour/Cminute/Csecond/Cdecisecond', $binstring);
    var_dump($values);
    

    Output:

    array(7) {
      'year' =>
      int(1970)
      'month' =>
      int(1)
      'day' =>
      int(1)
      'hour' =>
      int(0)
      'minute' =>
      int(10)
      'second' =>
      int(20)
      'decisecond' =>
      int(0)
    }
    

    Please refer to the following manual pages:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵