drwghu6386 2010-03-26 16:00
浏览 66
已采纳

检查字符串是否为unix时间戳

I have a string and I need to find out whether it is a unix timestamp or not, how can I do that effectively?

I found this thread via Google, but it doesn't come up with a very solid answer, I'm afraid. (And yes, I cribbed the question from the original poster on the aforementioned thread).

  • 写回答

11条回答 默认 最新

  • douchenchepan6465 2010-03-26 16:10
    关注

    Ok, after fiddling with this for some time, I withdraw the solution with date('U') and suggest to use this one instead:

    function isValidTimeStamp($timestamp)
    {
        return ((string) (int) $timestamp === $timestamp) 
            && ($timestamp <= PHP_INT_MAX)
            && ($timestamp >= ~PHP_INT_MAX);
    }
    

    This check will only return true if the given $timestamp is a string and consists solely of digits and an optional minus character. The number also has to be within the bit range of an integer (EDIT: actually unneeded as shown here).

    var_dump( isValidTimeStamp(1)             ); // false
    var_dump( isValidTimeStamp('1')           ); // TRUE
    var_dump( isValidTimeStamp('1.0')         ); // false
    var_dump( isValidTimeStamp('1.1')         ); // false
    var_dump( isValidTimeStamp('0xFF')        ); // false
    var_dump( isValidTimeStamp('0123')        ); // false
    var_dump( isValidTimeStamp('01090')       ); // false
    var_dump( isValidTimeStamp('-1000000')    ); // TRUE
    var_dump( isValidTimeStamp('+1000000')    ); // false
    var_dump( isValidTimeStamp('2147483648')  ); // false
    var_dump( isValidTimeStamp('-2147483649') ); // false
    

    The check for PHP_INT_MAX is to ensure that your string can be used correctly by date and the likes, e.g. it ensures this doesn't happen*:

    echo date('Y-m-d', '2147483648');  // 1901-12-13
    echo date('Y-m-d', '-2147483649'); // 2038-01-19
    

    On 64bit systems the integer is of course larger than that and the function will no longer return false for "2147483648" and "-2147483649" but for the corresponding larger numbers.


    (*) Note: I'm not 100% sure, the bit range corresponds with what date can use though

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(10条)

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能