PHP Parse Date String

后端 未结 8 1492
春和景丽
春和景丽 2021-01-11 18:14

If I\'ve got a date string:

$date = \"08/20/2009\";

And I want to separate each part of the date:

$m = \"08\";
$d = \"20\";         


        
相关标签:
8条回答
  • 2021-01-11 18:57

    If you have a given format you should use a date object.

    $date = DateTime::createFromFormat('m/d/Y', '08/20/2009');
    $m = $date->format('m');
    $d = $date->format('d');
    $y = $date->format('Y');
    

    Note you can certainly use only one call to DateTime::format().

    $newFormat = $date->format('d-m-Y');
    
    0 讨论(0)
  • 2021-01-11 19:03

    explode will do the trick for that:

    $pieces = explode("/", $date);
    $d = $pieces[1];
    $m = $pieces[0];
    $y = $pieces[2];
    

    Alternatively, you could do it in one line (see comments - thanks Lucky):

    list($m, $d, $y) = explode("/", $date);
    
    0 讨论(0)
  • 2021-01-11 19:06

    Dominic's answer is good, but IF the date is ALWAYS in the same format you could use this:

    $m = substr($date,0,2);
    $d = substr($date,3,2);
    $y = substr($date,-4);
    

    and not have to use an array or explode

    Bill H

    0 讨论(0)
  • 2021-01-11 19:07

    Is it always like that? Or will it be in any sort of file format?

    Try strtotime.

    Something like:

    if(($iTime = strtotime($strDate))!==false)
    {
     echo date('m', $iTime);
     echo date('d', $iTime);
     echo date('y', $iTime);
    }
    
    0 讨论(0)
  • 2021-01-11 19:13

    how about this:

    list($m, $d, $y) = explode("/", $date);
    

    A quick one liner.

    0 讨论(0)
  • 2021-01-11 19:16

    One way would be to do this:

    $time = strtotime($date);
    $m = date('m', $time);
    $d = date('d', $time);
    $y = date('Y', $time);
    
    0 讨论(0)
提交回复
热议问题