skip to Main Content

I am trying to change date format but its showing me wrong result (showing me 1970-01-01),How can i fix this, i want dynamic date in "Y-m-d" format,Here is my code

$start_date2=$_POST['start_date']; //showing 10-30-2022
echo $new_date = date("Y-m-d", strtotime($start_date2)); // showing 1970-01-01

2

Answers


  1. The upcoming date format in $start_date2=$_POST['start_date']; is incorrect that’s why you are getting an incorrect result

    So you need to first correct its format and then try to change its format to your desired one. check the code below

    <?php
    
    $start_date2='10-30-2022'; //date format inccorect
    $start_date2=str_replace('-','/',$start_date2); // correct date format
    echo $new_date = date("Y-m-d", strtotime($start_date2)); // now you will get correct result
    

    https://3v4l.org/dQHHA

    Reference : PHP Date Formats

    Important Note: try to change the date field format in your HTML form itself if possible, then you can directly do : $new_date = date("Y-m-d", strtotime($start_date2));

    Login or Signup to reply.
  2. If the POST value is "showing 10-30-2022", you are doing something very wrong.

    When you have a date field in a form it should look like:

    <input type="date" name="start_date" />
    

    The above will post a date value in the format of ‘Y-m-d’.

    That makes your date("Y-m-d", strtotime($start_date2)); superfluous.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search