简体   繁体   English

PHP将日期转换为mm-dd-YYYY到YYYY-mm-dd

[英]PHP convert date to mm-dd-YYYY to YYYY-mm-dd

My problem is that when I try to save in my database a date I receive this date: 1970-01-01 我的问题是,当我尝试在我的数据库中保存我收到此日期的日期: 1970-01-01

This is my html code: 这是我的HTML代码:

<input type="text" name="dob" value="<?php echo $rows['dob']; ?>" required title="The Date of Birth is required" pattern="(0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])[-](19|20)\d\d"></input>

And this my php code to get the value: 这是我的PHP代码获取值:

$dob = $_POST['dob'];
echo $dob.'<br>';
$dob_new = date('Y-m-d', strtotime($dob));
echo $dob_new.'<br>';

This is the result: 这是结果:

01-22-1984
1970-01-01

The first date is one example that a date that the user can enter and the second date is the result of the conversion! 第一个日期是用户可以输入的日期和第二个日期是转换结果的一个示例!

The mystery is that sometimes this work but sometimes no... so what happen here? 神秘之处在于,有时候这项工作有时却没有...所以这里发生了什么? Any suggestion? 有什么建议吗? Any error in my code? 我的代码中有错误吗?

When you use dashes as your date separator PHP assumes European date format which is DD-MM-YYYY. 当您使用短划线作为日期分隔符时,PHP假定为欧洲日期格式,即DD-MM-YYYY。 Yours is MM-DD-YYYY. 你的是MM-DD-YYYY。 As a result strtotime() thinks it has an invalid date and returns false which causes date() to return the date you are seeing which is the Unix Epoch. 因此strtotime()认为它有一个无效的日期并返回false,这会导致date()返回您看到的日期,即Unix Epoch。

To work around it you either need to send the date in the correct format or use DateTime::createFromFormat() to parse the date properly. 要解决此问题,您需要以正确的格式发送日期或使用DateTime::createFromFormat()来正确解析日期。

$date = DateTime::createFromFormat('m-d-Y', $_POST['dob']);
$dob_new = $date->format('Y-m-d');

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM