programing

문자열이 날짜인지 확인하는 기능

sourcetip 2021. 1. 16. 11:17
반응형

문자열이 날짜인지 확인하는 기능


PHP를 사용하여 문자열이 날짜 / 시간인지 확인하는 함수를 작성하려고합니다. 기본적으로 유효한 날짜 / 시간은 다음과 같습니다.

 2012-06-14 01:46:28

분명히 완전히 동적 인 값은 변경 될 수 있지만 항상 형식이어야 XXXX-XX-XX XX:XX:XX합니다.이 패턴을 확인하고 일치하는 경우 true를 반환하는 정규식을 어떻게 작성할 수 있습니까?


이것이 전체 문자열이면 구문 분석을 시도하십시오.

if (DateTime::createFromFormat('Y-m-d H:i:s', $myString) !== FALSE) {
  // it's a date
}

다음은 정규식을 사용하지 않는 다른 접근 방식입니다.

function check_your_datetime($x) {
    return (date('Y-m-d H:i:s', strtotime($x)) == $x);
}

날짜 형식을 모르는 경우 :

/**
 * Check if the value is a valid date
 *
 * @param mixed $value
 *
 * @return boolean
 */
function isDate($value) 
{
    if (!$value) {
        return false;
    }

    try {
        new \DateTime($value);
        return true;
    } catch (\Exception $e) {
        return false;
    }
}

var_dump(isDate('2017-01-06')); // true
var_dump(isDate('2017-13-06')); // false
var_dump(isDate('2017-02-06T04:20:33')); // true
var_dump(isDate('2017/02/06')); // true
var_dump(isDate('3.6. 2017')); // true
var_dump(isDate(null)); // false
var_dump(isDate(true)); // false
var_dump(isDate(false)); // false
var_dump(isDate('')); // false
var_dump(isDate(45)); // false

더 작은 버전이면 도움이 될 수 있습니다.

if(strtotime($date_string)){
    // it's in date format
}

이 함수를 PHP filter_var함수 의 매개 변수로 사용 합니다.

  • yyyy-mm-dd hh:mm:ss형식의 날짜를 확인 합니다.
  • 패턴과 일치하지만 여전히 유효하지 않은 날짜는 거부합니다 (예 : 4 월 31 일).

function filter_mydate($s) {
    if (preg_match('@^(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$@', $s, $m) == false) {
        return false;
    }
    if (checkdate($m[2], $m[3], $m[1]) == false || $m[4] >= 24 || $m[5] >= 60 || $m[6] >= 60) {
        return false;
    }
    return $s;
}

Although this has an accepted answer, it is not going to effectively work in all cases. For example, I test date validation on a form field I have using the date "10/38/2013", and I got a valid DateObject returned, but the date was what PHP call "overflowed", so that "10/38/2013" becomes "11/07/2013". Makes sense, but should we just accept the reformed date, or force users to input the correct date? For those of us who are form validation nazis, We can use this dirty fix: https://stackoverflow.com/a/10120725/486863 and just return false when the object throws this warning.

The other workaround would be to match the string date to the formatted one, and compare the two for equal value. This seems just as messy. Oh well. Such is the nature of PHP dev.


I wouldn't use a Regex for this, but rather just split the string and check that the date is valid:

list($year, $month, $day, $hour, $minute, $second) = preg_split('%( |-|:)%', $mydatestring);
if(!checkdate($month, $day, $year)) {
     /* print error */
} 
/* check $hour, $minute and $second etc */

strtotime? Lists? Regular expressions?

What's wrong with PHP's native DateTime object?

http://www.php.net/manual/en/datetime.construct.php


If your heart is set on using regEx then txt2re.com is always a good resource:

<?php

  $txt='2012-06-14 01:46:28';
  $re1='((?:2|1)\\d{3}(?:-|\\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9]))';    # Time Stamp 1

  if ($c=preg_match_all ("/".$re1."/is", $txt, $matches))
  {
      $timestamp1=$matches[1][0];
      print "($timestamp1) \n";
  }

?>

If you have PHP 5.2 Joey's answer won't work. You need to extend PHP's DateTime class:

class ExDateTime extends DateTime{
    public static function createFromFormat($frmt,$time,$timezone=null){
        $v = explode('.', phpversion());
        if(!$timezone) $timezone = new DateTimeZone(date_default_timezone_get());
        if(((int)$v[0]>=5&&(int)$v[1]>=2&&(int)$v[2]>17)){
            return parent::createFromFormat($frmt,$time,$timezone);
        }
        return new DateTime(date($frmt, strtotime($time)), $timezone);
    }
}

and than you can use this class without problems:

ExDateTime::createFromFormat('d.m.Y G:i',$timevar);

 function validateDate($date, $format = 'Y-m-d H:i:s') 
 {    
     $d = DateTime::createFromFormat($format, $date);    
     return $d && $d->format($format) == $date; 
 } 

function was copied from this answer or php.net


In my project this seems to work:

function isDate($value) {
    if (!$value) {
        return false;
    } else {
        $date = date_parse($value);
        if($date['error_count'] == 0 && $date['warning_count'] == 0){
            return checkdate($date['month'], $date['day'], $date['year']);
        } else {
            return false;
        }
    }
}

if (strtotime($date)>strtotime(0)) { echo 'it is a date' }

ReferenceURL : https://stackoverflow.com/questions/11029769/function-to-check-if-a-string-is-a-date

반응형