Check whether the string is a unix timestamp

后端 未结 12 1731
挽巷
挽巷 2020-11-27 16:43

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

相关标签:
12条回答
  • 2020-11-27 16:50

    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:

    ( is_numeric($stamp) && (int)$stamp == $stamp )
    
    0 讨论(0)
  • 2020-11-27 16:51
        //if anything else than digits inside the string then your string is no timestamp 
        //in which case maybe try to get the timestamp with strtotime
    
        if(preg_match('/[^\d]/', $str)) {
            $str = strtotime($str);
    
            if (false === $str) {
                //conversion failed - invalid time - invalid row
                return;
            }
        }
    
    0 讨论(0)
  • 2020-11-27 16:53

    If you might think to replace this solution 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.

    0 讨论(0)
  • 2020-11-27 16:53

    In PHP for checking if a timestamp represents a valid Gregorian date this worked for me:

    function checkdateTimestamp($timestamp) {
        return checkdate((int)date('m',$timestamp),(int)date('d',$timestamp),(int)date('Y',$timestamp));
    }
    
    0 讨论(0)
  • 2020-11-27 16:56

    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)

    $valid = ctype_digit($str) && $str <= 2147483647;
    
    0 讨论(0)
  • 2020-11-27 16:58

    or

    if ($startDate < strtotime('-30 years') || $startDate > strtotime('+30 years')) {
        //throw exception
    }
    
    0 讨论(0)
提交回复
热议问题