Convert MMDDYYYY to date for PHP

前端 未结 6 712
你的背包
你的背包 2021-01-14 10:46

I have a string with a date which is in this format MMDDYYYY (ie. 01132012, 01142012 etc.)

I need to do something on a page, if that string is 14 days or less from t

6条回答
  •  深忆病人
    2021-01-14 11:18

    Your string input of '01142012' cannot be parsed by strtotime() as it is not a valid as it is returning -1 as an answer. To convert this into a valid date you will need to add either slashes or dashes to separate the numbers.

    The easiest way would be to store the dates with the dashes or slashes, such as '01-14-2012' or '01/14/2012' in the database from now on or you are going to have to create your own function to convert the numbers into a valid form for strtotime().

    To do this you could do something like this:

    function makeValidDate($date) {
    
       $valid_date = array();
       $array = str_split($date); //split characters up
    
       foreach($array as $key => $character){
           if($key==2 || $key==4){
               $character = '-'.$character; //add relevant formatting to date
               $valid_date[] = $character; //add this to the formatted array
           }
           else{
               $valid_date[] = $character; // if not dashes or slashes needed add to valid array
           }
       }
    
       return implode($valid_date); // return the formmatted date for use with strtotime
    }
    

    You can then do this to get a valid date:

    $valid_date = makeValidDate('01142012');    
    echo date("d/m/Y", strtotime($valid_date));
    

    I haven't tested this but you should get a good idea of what to do.

    EDIT: Capi's idea is a lot cleaner!!

提交回复
热议问题