当数据库中存在冲突的日期系统时,当发生这种情况时,会导致PHP中的混乱。例如,如果数据库中的部分日期包含了2016年1月1日的日期,但在另一个时间点上却包含了2016年1月1日的日期,那么日期系统似乎就会崩溃。在适当的环境中,我认为这应该是划时代的,但在这种情况下,情况并非如此。
下面的代码很混乱,也许我想得太多了。但这就是我所拥有的
/*
*
* Dates ($dob) can appear as followed:
* 01-30-2016 | 1-30-2016 | 01-01-2016 | 01/30/2016 or any combination
*
*/
$chpos = 0; // Define Character Position Variable
$replace = false; // Should we replace the 0 after the first dash?
// If the date uses this format: 01/02/2016 then replace the / with - so it looks like 01-02-2016
$dob = preg_replace('/\s+/', '-', $dob);
// Let's find out if the dash occurs on the 3rd character or 4th. We do this so we can replace the 0 in 2-02-2016
// 01-34-6789 *String Array positions* 0-23-5678
if(substr($dob, 0, 3) == 0 && substr($dob, 0, 0) == 0){
$chpos = 3;
$replace == true;
} else if (substr($dob, 0, 0) != 0 && substr($dob, 0, 2) == 0){
$chpos = 2;
$replace == true;
} else {
$replace == false;
}
// Let's replace the 0 after the first dash if necessary
if($replace == true){
$dob = substr_replace($dob, '', $chpos);
}
// Let's replace the 0 from the beginning if necessary
if(substr($dob, 0, 1 ) == 0){
$dob = substr( $dob, 1 );
}
// Let's convert it to a usable date object
$birthday = new DateTime($dob);
// Now let's compare the time from now to when the birthdate happened
$interval = $birthday->diff(new DateTime);
// Return the data over
return $interval->y;
代码的问题与当它替换事物左边的0时有关。我可以发誓代码应该工作,但也许我做了一个错误,只是看不到它?我不知道,但根本没用。其信息是:
Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (2-17-1994) at position 0 (2): Unexpected character'
参考的行是:$birthday =新的DateTime($dob);
我的问题是:
谢谢您抽时间见我!
发布于 2016-09-08 07:50:29
忽略数据清理的问题(道布不应该以不同的格式进入数据库;使用unix时间戳是一个更好的选择).为什么不做以下几件事;
$timedob = strtotime($dob);
$birthday = date('Y-m-d',$timedob);
strtotime接受任何字符串并将其转换为unix时间戳。然后,date函数将unix时间戳转换为所需的输出格式。
请注意,strtotime将输入解释如下;如果月、日、年用斜杠“/”分隔,则假定日期为美国的m/d/y格式。如果它看到连字符或句点(-或.),则假定日期为欧洲d格式。
发布于 2016-09-08 07:54:52
在php中解析日期字符串是非常容易的,它花费了非常长的时间来最好地使用像strtottime这样的函数来解释字符串。http://php.net/manual/en/function.strtotime.php
您遇到的问题是,您应该将数据库中的日期存储为数据库日期或日期时间格式(或数据库的任何等效格式)。在尝试将它们输入数据库之前,应该先进行验证,以及测试任何数据库写入都不会因为格式糟糕的日期结构而被拒绝。在转换到输出日期时,还应该进行进一步的验证。
很长一段时间以来,我不得不像您在这里所做的那样手动操作日期字符串,当然没有必要这样做。特别是由于日期选择器非常常见,在发送之前也会通过js格式化日期浏览器端。(这当然不能消除服务器端验证的需要。)
如果我是您,我将编写一个简短的脚本,将您的所有日期转换为数据库的适当日期格式,并将该数据库列的格式更改为日期格式。然后,将试图将字符串作为日期写入应用程序中数据库的任何位置进行地址处理。在结构良好的应用程序中,这应该只在一个模型函数中完成,所以不应该花费太长时间。
正确执行此操作的最后一个好处是,您现在可以轻松地生成报表或查询结果,例如在此之前发生的每个事件,日期或两个日期之间,或星期二,等等。
https://stackoverflow.com/questions/39395206
复制相似问题