检查字符串是否为unix时间戳 [英] Check whether the string is a unix timestamp

查看:811
本文介绍了检查字符串是否为unix时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,我需要找出是否是一个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).

推荐答案

好的,有一段时间,我用 date('U')撤回解决方案,建议使用这个代替:

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

检查PHP_INT_MAX是确保您的字符串可以正确使用 date 和喜欢,例如它确保这不会发生*:

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

在64位系统上,整数当然大于该值,函数将不会再为2147483648和-2147483649返回假,但对应的较大数字。

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.

(*)注意:我不是100%肯定的,这个位范围对应于可以使用的日期

这篇关于检查字符串是否为unix时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆