Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP date showing '1970-01-01 ' after conversion

I have a form in which date format is dd/mm/yyyy . For searching database , I hanverted the date format to yyyy-mm-dd . But when I echo it, it showing 1970-01-01 . The PHP code is below:

$date1 = $_REQUEST['date'];     
echo date('Y-m-d', strtotime($date1));

Why is it happening? How can I format it to yyyy-mm-dd?

like image 283
AssamGuy Avatar asked Jan 24 '12 09:01

AssamGuy


People also ask

How can I get current date in YYYY MM DD format in PHP?

$date = date("yyyy-mm-dd", strtotime(now));

How convert date from yyyy mm dd to dd-mm-yyyy format in PHP?

Answer: Use the strtotime() Function You can first use the PHP strtotime() function to convert any textual datetime into Unix timestamp, then simply use the PHP date() function to convert this timestamp into desired date format. The following example will convert a date from yyyy-mm-dd format to dd-mm-yyyy.


3 Answers

Replace / with -:

$date1 = strtr($_REQUEST['date'], '/', '-');
echo date('Y-m-d', strtotime($date1));
like image 135
Cyclonecode Avatar answered Oct 11 '22 16:10

Cyclonecode


January 1, 1970 is the so called Unix epoch. It's the date where they started counting the Unix time. If you get this date as a return value, it usually means that the conversion of your date to the Unix timestamp returned a (near-) zero result. So the date conversion doesn't succeed. Most likely because it receives a wrong input.

In other words, your strtotime($date1) returns 0, meaning that $date1 is passed in an unsupported format for the strtotime function.

like image 35
Oldskool Avatar answered Oct 11 '22 16:10

Oldskool


$date1 = $_REQUEST['date'];

if($date1) {
    $date1 = date( 'Y-m-d', strtotime($date1));
} else {
    $date1 = '';
}

This will display properly when there is a valid date() in $date and display nothing if not.
Solved the issue for me.

like image 1
Tye Lucas Avatar answered Oct 11 '22 17:10

Tye Lucas