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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2524680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:49:31  来源:igfitidea点击:

Check whether the string is a unix timestamp

phpdatetimetimeunix-timestamp

提问by RHPT

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

我有一个字符串,我需要确定它是否是 unix 时间戳,我怎样才能有效地做到这一点?

I found this threadvia 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).

我通过谷歌找到了这个线程,但恐怕没有给出一个非常可靠的答案。(是的,我从上述线程的原始海报中抄袭了这个问题)。

回答by Gordon

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

好的,在摆弄了一段时间后,我撤回了解决方案date('U')并建议改用这个:

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 $timestampis a stringand 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).

如果给定的$timestamp字符串并且仅由数字和可选的减号组成,则此检查将仅返回 true 。该数字还必须在整数的位范围内(编辑实际上不需要,如此处所示)。

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 dateand the likes, e.g. it ensures this doesn't happen*:

检查 PHP_INT_MAX 是为了确保您的字符串可以被诸如此类的人正确使用date,例如它确保不会发生这种情况*:

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.

在 64 位系统上,整数当然比那个大,函数将不再为“2147483648”和“-2147483649”返回假,而是为相应的更大的数字返回假。



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

(*)注意:我不是 100% 确定,位范围与可以使用的日期相对应

回答by Yacoby

As a unix timestamp is a integer, use is_int(). However as is_int() doesn't work on strings, we check if it is numeric and its intergal form is the same as its orignal form. Example:

由于 unix 时间戳是整数,因此请使用is_int()。然而,由于is_int() 不适用于字符串,我们检查它是否是数字并且它的整数形式与其原始形式相同。例子:

( is_numeric($stamp) && (int)$stamp == $stamp )

回答by simplychrislike

I came across the same question and created the following solution for my self, where I don't have to mess with regular expressions or messy if-clauses:

我遇到了同样的问题,并为我自己创建了以下解决方案,在那里我不必弄乱正则表达式或凌乱的 if 子句:

/**
 * @param string $string
 * @return bool
 */
public function isTimestamp($string)
{
    try {
        new DateTime('@' . $string);
    } catch(Exception $e) {
        return false;
    }
    return true;
}

回答by TD_Nijboer

this looks like the way to go:

这看起来像要走的路:

function is_timestamp($timestamp) {
    if(strtotime(date('d-m-Y H:i:s',$timestamp)) === (int)$timestamp) {
        return $timestamp;
    } else return false;
}

you could also add a is_numeric() check and all sort of other checks.
but this should/could be the basics.

您还可以添加 is_numeric() 检查和所有其他检查。
但这应该/可能是基础知识。

回答by Dimitar Darazhanski

Improved answer to @TD_Nijboer.

改进了对@TD_Nijboer 的回答。

This will avoid an exception be thrown if the supplied string is not a time stamp:

如果提供的字符串不是时间戳,这将避免抛出异常:

function isTimestamp($timestamp) {
    if(ctype_digit($timestamp) && strtotime(date('Y-m-d H:i:s',$timestamp)) === (int)$timestamp) {
        return true;
    } else {
        return false;
}

回答by goat

This doesn't account for negative times(before 1970), nor does it account for extended ranges(you can use 64 bit integers so that a timestamp can represent a value far after 2038)

这不考虑负时间(1970 年之前),也不考虑扩展范围(您可以使用 64 位整数,以便时间戳可以表示远在 2038 年之后的值)

$valid = ctype_digit($str) && $str <= 2147483647;

回答by Patrick Cornelissen

You want to check if a string contains a high number?

你想检查一个字符串是否包含一个大数字?

is_numeric() is the key

is_numeric() 是关键

Or convert it to DateTime and do some checks with it like an expected date range.

或者将其转换为 DateTime 并对其进行一些检查,例如预期的日期范围。

回答by alex toader

or

或者

if ($startDate < strtotime('-30 years') || $startDate > strtotime('+30 years')) {
    //throw exception
}

回答by Aleksandr Matiushkin

If you might think to replace thissolution with is_numeric(), please consider that php native function provides false positives for input strings like "1.1", "0123", "0xFF" which are not in timestamp format.

如果您可能想用is_numeric()替换解决方案,请考虑 php 本机函数为诸如“1.1”、“0123”、“0xFF”之类的非时间戳格式的输入字符串提供误报。

回答by Chris

Another possibility:

另一种可能:

$date_arg = time();
$date_is_ok = ($date_arg === strtotime(date('c', $date_arg)));