PHP - How to get year, month, day from time string

后端 未结 4 1009
粉色の甜心
粉色の甜心 2020-12-15 18:18

Given the following timestring:

$str = \'2000-11-29\';

$php_date = getdate( $str );
echo \'
\';
print_r ($php_date);
echo \'
\';
相关标签:
4条回答
  • 2020-12-15 19:07

    You can use strtotime to parse a time string, and pass the resulting timestamp to getdate (or use date to format your time).

    $str = '2000-11-29';
    
    if (($timestamp = strtotime($str)) !== false)
    {
      $php_date = getdate($timestamp);
      // or if you want to output a date in year/month/day format:
      $date = date("Y/m/d", $timestamp); // see the date manual page for format options      
    }
    else
    {
      echo 'invalid timestamp!';
    }
    

    Note that strtotime will return false if the time string is invalid or can't be parsed. When the timestamp you're trying to parse is invalid, you end up with the 1969-12-31 date you encountered before.

    0 讨论(0)
  • 2020-12-15 19:09

    Update: Forgot to add semicolon at end of first line, try this:

    <?php       
    $str = "2010-08-29"; // Missed semicolon here
    $time = strtotime($str);
    
    // You can now use date() functions with $time, like
    $weekday = date("l", $time); // Wednesday or whatever date it is    
    ?>
    

    Hopefully that will get you going!

    0 讨论(0)
  • 2020-12-15 19:10

    Using the object-oriented programming style, you can do this with DateTime class

    $dateFormat = 'Y-m-d';
    $stringDate = '2000-11-29';
    $date = DateTime::createFromFormat($dateFormat, $stringDate);
    

    Then, you can decompose your date using the format() method

    $year = $date->format('Y'); // returns a string
    

    If you prefer the numeric format, instead of the string format, you can use the intval() function

    $year = intval($date->format('Y')); // returns an integer
    

    Here some formats that you can use

    • Y A full numeric representation of a year, 4 digits
    • m Month of the year, 2 digits with leading zeros
    • d Day of the month, 2 digits with leading zeros
    • H 24-hour format of an hour, 2 digits with leading zeros
    • i Minutes, 2 digits with leading zeros
    • s Seconds, 2 digits with leading zeros

    Here the entire list of the formats that you can use : http://php.net/manual/en/function.date.php

    0 讨论(0)
  • 2020-12-15 19:16

    PHP - How to get year, month, day from time string

    $dateValue = strtotime($q);                     
    
    $yr = date("Y", $dateValue) ." "; 
    $mon = date("m", $dateValue)." "; 
    $date = date("d", $dateValue); 
    
    0 讨论(0)
提交回复
热议问题