Search code examples
phpdatedate-formatdate-conversion

What's the issue in converting date from one format to another in following function code?


I tried following code to convert date from mm-dd-yy format to yyyy-mm-dd format.

function format_date_yyyy_mm_dd($date_val){ 
      if(!empty($date_val)) {
        $newDate = date("m-d-Y", strtotime($date_val));

        return $newDate;        
      } else 
        return false;            
    }

Suppose, the argument passed($date_val) contains the value 4-26-1991 after executing the function I'm getting the return value as 01-01-1970 instead of the desired value 1991-04-26. How to resolve this issue? Can someone please help me? In addition if you provide me the function to reverse the above procees of date conversion it will be really very helpful to me.

Thanks in advance.


Solution

  • Use the DateTime class for stuff like this. Since you have a given format (n-j-Y), you can pass it into the createFromFormat() method:

    function format_date_yyyy_mm_dd($date_val) {
        $date = \DateTime::createFromFormat('n-j-Y', $date_val);
        return $date->format('Y-m-d');
    }
    

    For the reverse function, the normal constructor will suffice as it will be able to read the standard ISO8601 format (YYYY-MM-DD):

    function format_date_mm_dd_yy($date_val) {
        $date = new \DateTime($date_val);
        return $date->format('n-j-Y');
    }