Theo Theo - 4 months ago 8
MySQL Question

php date format returns 01-01-1970

In my php code I insert some data in my database. One them is the date. I want to be displayed in the format of 27-08-2016 but I get back 01-01-1970

This is my code.

<?php
include("./init.php");

if(isset($_POST['submit'])){

$post_game = $_POST['game'];

$time = strtotime($_POST['date']);

$post_date = date("d-m-Y", strtotime($time));

if($post_game==''){

echo "<script>alert('Please fill in all fields')</script>";
exit();
}
else {

$insert_game = "insert into last_game (game,date) values ('$post_game','$post_date')";

$run_posts = mysqli_query($con,$insert_game);

echo "<script>alert('Post Has been Published!')</script>";

echo "<script>window.open('index.php?last_game_details','_self')
</script>";

}

}

?>


The crucial line is:

$post_date = date("d-m-Y", strtotime($time));


and my php version is:5.6.23

Answer

Please use Now() in query to insert current date. NOW() returns the current date and time.

if(isset($_POST['submit'])){

 $post_game = $_POST['game'];

 $time = strtotime($_POST['date']);

 $post_date = date("d-m-Y", strtotime($time));

if($post_game==''){

    echo "<script>alert('Please fill in all fields')</script>";
    exit();
    }
else {

    $insert_game = "insert into last_game (game,date) values ('$post_game',NOW())";

    $run_posts = mysqli_query($con,$insert_game); 

        echo "<script>alert('Post Has been Published!')</script>";

        echo "<script>window.open('index.php?last_game_details','_self')   
   </script>";

     }

   }

?> 

To retrieve your required format of date use php

`echo date_format($date,"Y-m-d ");`