Resultado de la inserción en la base de datos mysql en la marca de tiempo UNIX

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

preguntado el 30 de julio de 12 a las 06:07

The answer you link to converts dd/mm/yyyy a yyyy-mm-dd, y eso es diferente de mm/dd/yyyy aporte. -

6 Respuestas

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 para más detalles.

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.

Lo siguiente debería funcionar

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

Respondido 30 Jul 12, 06:07

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.

Respondido 30 Jul 12, 06:07

Thanks CyberDemon...its working. Can you explain or just give a help link,I will b grtful to u - Nitish

I had used regular expression to modify string (reorder numbers and replace slash to dash). - CyberDem0n

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

put double quotes in date then you get perfect result

Respondido 30 Jul 12, 06:07

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.

Respondido 30 Jul 12, 06:07

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)

Respondido 30 Jul 12, 06:07

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 /.

Respondido 30 Jul 12, 06:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.