DateTime :: createFromFormat in PHP <5.3.0

I am looking for a function identical to DateTime :: createFromFormat , but I need it to work in an environment with a version of PHP that is older than v5.3. Basically, I need to provide a format, for example, using the Date () function , and then I need to parse / check the string against this format and return a timestamp if the string is formatted correctly and a valid date.

Does anyone know where I can find something like this, or can I write it myself?

Again, this should work with the specific format provided as an argument. The format can be any, so there is no guarantee that I can just use strtotime () .

+3
source share
5 answers

DateTime::createFromFormatand date_parse_from_formatwere added in PHP 5.3 because there was a high demand for this function, especially for developers who code users who do not use US date and time formats.


Before that, you had to develop a specific function to analyze the format you are using; with PHP <5.3, which is usually done:

  • Determine which format the application will accept
  • Display a message that says "your entry must be JJ / MM / AAAA" (French for DD / MM / YYYY)
  • Make sure the input is ok in relation to this format
  • And parse it to convert it to a date / time that PHP can understand.

, , + .


, , , : - (

, date_parse_from_format , C-? - ext/date/php_date.c - : timelib_parse_from_format, ext/data/lib/parse_date.c, ^^

+6

Zend_Date Zend Framework: http://framework.zend.com/manual/en/zend.date.html

$date = new Zend_Date($string, $format);
$timestamp = $date->get();
+4

strptime() - strftime(). date(), .

function createFromFormat($strptimeFormat, $date) {
    $date = strptime($date, $strptimeFormat);
    $date['tm_year'] += 1900;
    $date['tm_mon']++;
    $timestamp = mktime($date['tm_hour'], $date['tm_min'], $date['tm_sec'], $date['tm_mon'], $date['tm_mday'], $date['tm_year']);
    return new DateTime('@'. $timestamp);
}
+3

PHP 5.3 , DateTime , 'DD.MM.YYYY'.

function ParseForDateTimeValue ($strText)
{
    if ($strText != "")
    {
        if (ereg("^([0-9]{1,2})[/\.]\s*([0-9]{1,2})[/\.]\s*([0-9]{2,4})$",$strText,$arr_parts)) {

            $month = ltrim($arr_parts[2], '0');
            $day = ltrim($arr_parts[1], '0');
            $year = $arr_parts[3];

            if (checkdate($month, $day, $year)) {
               return new DateTime(date('Y-m-d H:i:s', mktime(0, 0, 0, $month, $day, $year));
            }
        }
    }
    return NULL;
}
  • .
  • , .
  • checkdate .
  • DateTime .
+1

timestamp, .., timestamp, explode , .

$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
echo "Tomorrow is ".date("Y/m/d", $tomorrow);
0

Source: https://habr.com/ru/post/1733921/


All Articles