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
Dates in the m/d/y or dmy 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 dmy 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']));
echo $date = preg_replace('/^(\d\d)\/(\d\d)\/(\d{4})$/', '$3-$1-$2', $_POST['date']);
我认为这段代码应该可以正常工作,但是在将其插入数据库之前,您当然必须进行所有必要的检查。
echo $date1 = str_replace("/","-","$_POST['date']");
echo $date = date('Y-m-d', strtotime($date1));
put double quotes in date then you get perfect result
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.
echo $date = date('Ym-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)
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 /
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.