36

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?

always-a-learner
  • 3,671
  • 10
  • 41
  • 81
AssamGuy
  • 1,571
  • 10
  • 30
  • 43

8 Answers8

87

Replace / with -:

$date1 = strtr($_REQUEST['date'], '/', '-');
echo date('Y-m-d', strtotime($date1));
Cyclonecode
  • 29,115
  • 11
  • 72
  • 93
36

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.

Oldskool
  • 34,211
  • 7
  • 53
  • 66
  • Thus, putting a condition like`if (strtotime($date1))` before the conversion seems like a good practice. – joeljpa Mar 02 '23 at 11:17
2
$inputDate = '07/05/-0001';
$dateStrVal = strtotime($inputDate);
if(empty($dateStrVal))
{
  echo 'Given date is wrong'; 
}
else{
 echo 'Date is correct';
}

O/P : Given date is wrong

Kaushal Roy
  • 159
  • 1
  • 6
1
$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.

Axel
  • 3,331
  • 11
  • 35
  • 58
Tye Lucas
  • 107
  • 1
  • 1
  • 9
0

Another workaround:

Convert datepicker dd/mm/yyyy to yyyy-mm-dd

$startDate = trim($_POST['startDate']);
$startDateArray = explode('/',$startDate);
$mysqlStartDate = $startDateArray[2]."-".$startDateArray[1]."-".$startDateArray[0];
$startDate = $mysqlStartDate;
0

The issue is when your data is set to 000-00-00 or empty you must double-check and give the correct information and this issue will go away. I hope this helps.

jerryurenaa
  • 3,863
  • 1
  • 27
  • 17
-1

Use below code for php 5.3+:

$date = new DateTime('1900-02-15');
echo $date->format('Y-m-d');

Use below code for php 5.2:

$date = new DateTime('1900-02-15');
echo $date->format('Y-m-d');
Dayz
  • 269
  • 2
  • 12
-2

finally i have found a one line code to solve this problem

date('d/m/Y', strtotime(str_replace('.', '-', $row['DMT_DATE_DOCUMENT'])));
Bakhtawar GIll
  • 407
  • 5
  • 16
  • 2
    What kind of answer is this, you picked code from everyone else and put it on one line? Have you ever heard about code readability? – Cyclonecode Feb 09 '16 at 13:36