Php 对布尔函数的成员函数format()的调用
我想找出两个日期之间的差异,我使用了Php 对布尔函数的成员函数format()的调用,php,date,Php,Date,我想找出两个日期之间的差异,我使用了date\u diff。当格式化函数应用于date\u diff对象时,它返回一个错误 调用布尔函数上的成员函数format() $field\u值从数据库中获取,其格式为dd/mm/YYYY。当我硬编码$field\u value和$indexing\u value的值时,以下代码起作用 在8号线之前一切都很好。我已尝试输出 $diff->format("%R%a") 它返回的是精确的值,但代码在if语句附近给出了错误 $date = new Dat
date\u diff
。当格式化函数应用于date\u diff
对象时,它返回一个错误
调用布尔函数上的成员函数format()
$field\u值
从数据库中获取,其格式为dd/mm/YYYY
。当我硬编码$field\u value
和$indexing\u value
的值时,以下代码起作用
在8号线之前一切都很好。我已尝试输出
$diff->format("%R%a")
它返回的是精确的值,但代码在if语句附近给出了错误
$date = new DateTime();
$current_date = $date->format('d/m/Y');
$indexing_value = str_replace("/", "-", $field_value);
$current_value = str_replace("/", "-", $current_date);
$indexing_value = date_create($indexing_value);
$current_value = date_create($current_value);
$diff = date_diff($indexing_value, $current_value);
if ($diff->format("%R%a") < 0) {
echo "1";
} else {
echo "2";
}
$date=new DateTime();
$current_date=$date->format('d/m/Y');
$index_value=str_replace(“/”、“-”、$field_value);
$current\u value=str\u replace(“/”、“-”、$current\u date);
$indexing\u value=date\u create($indexing\u value);
$current\u value=创建日期($current\u value);
$diff=date\u diff($index\u value,$current\u value);
如果($diff->format(“%R%a”)<0){
回声“1”;
}否则{
回声“2”;
}
请告诉我上面的代码有什么问题。添加条件以检查您是否获得差异,因为如果有错误,它将返回false。检查是否相同
$diff = date_diff($indexing_value, $current_value);
if ($diff) {
if ($diff->format("%R%a") < 0) {
echo "1";
}else{
echo "2";
}
}
$diff=date\u diff($index\u value,$current\u value);
如果($diff){
如果($diff->format(“%R%a”)<0){
回声“1”;
}否则{
回声“2”;
}
}
出现错误的原因是,对于某些值,差异未计算,并且在$diff
中有值False
请让我知道上面的代码有什么问题
该代码有几个问题:
$date
然后从结果字符串创建$current\u值
有什么意义?如果您不关心时间组件,只需要使用DateTime
对象的日期部分,则可以使用其setTime()
方法将时间组件设置为0
DateTime
对象0
进行比较。可以直接比较DateTime
对象// Current date & time
$today = new DateTime();
// Ignore the time (change $today to "today at midnight")
$today->setTime(0, 0, 0);
// Parse the value retrieved from the database
$field = DateTime::createFromFormat('d/m/Y', $field_value);
// We don't care about the time components of $field either (because the time
// is not provided in the input string it is created using the current time)
$field->setTime(0, 0, 0);
// Directly compare the DateTime objects to see which date is before the other
if ($field < $today) {
echo "1";
} else {
echo "2";
}
//当前日期和时间
$today=新日期时间();
//忽略时间(将$today更改为“今天午夜”)
$today->setTime(0,0,0);
//解析从数据库检索到的值
$field=DateTime::createFromFormat('d/m/Y',$field\u值);
//我们也不关心$field的时间组件(因为时间
//在使用当前时间创建的输入字符串中未提供)
$field->setTime(0,0,0);
//直接比较DateTime对象以查看哪个日期早于另一个日期
如果($field<$day){
回声“1”;
}否则{
回声“2”;
}