0

I have a strange problem . I am trying to insert some values to database with respective date . In HTML form, the date format is mm/dd/yyyy format. I converted this format to mysql yyyy-mm-dd format using the following PHP (from stackoverflow answer):

echo $date1 = str_replace("/","-",$_POST['date']);
echo $date = date('Y-m-d', strtotime($date1));

But the above echo , when I run the code it shows like this: 07-30-2012 1970-01-01

Community
  • 1
  • 1
Nitish
  • 2,695
  • 9
  • 53
  • 88
  • The answer you link to converts `dd/mm/yyyy` to `yyyy-mm-dd`, and that is different from `mm/dd/yyyy` input. – Arjan Jul 30 '12 at 05:44

6 Answers6

3

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. See http://php.net/manual/en/function.strtotime.php for details.

So even you are passing '07-30-2012' as an input, it is considering 07 as date, 30 as month hence you are getting incorrect results.

Following should work

echo $date = date('Y-m-d', strtotime($_POST['date']));
Dr. Dan
  • 2,288
  • 16
  • 19
1
echo $date = preg_replace('/^(\d\d)\/(\d\d)\/(\d{4})$/', '$3-$1-$2', $_POST['date']);

I think this code should work fine, but of course you must do all necessary checks before insert it into database.

CyberDem0n
  • 14,545
  • 1
  • 34
  • 24
1
echo $date1 = str_replace("/","-","$_POST['date']");
echo $date = date('Y-m-d', strtotime($date1));

put double quotes in date then you get perfect result

naveen
  • 1,078
  • 1
  • 13
  • 26
0

I've just tried :

$date = "30/07/2012";
echo $date1 = str_replace("/","-",$date);
echo '<br />';
echo $date = date('Y-m-d', strtotime($date1));

And it's actually returning :

30-07-2012
2012-07-30

You should check your $_POST['date'] format.

Jerska
  • 11,722
  • 4
  • 35
  • 54
0

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

Your first line is incorrect, which returns false, which (converted to an integer) is 0, 0 is the beginning of time on a linux machine! (hence 1970-01-01)

Matt Lo
  • 5,442
  • 1
  • 21
  • 21
0

Your input is in mm/dd/yyyy format, that means you should use slashes / You would need to change to dashes if you were using dd-mm-yyyy format, as is shown in the answer you link to. So in your case you should not replace the /.

Arjan
  • 9,784
  • 1
  • 31
  • 41