php DateTime,带日期,不带小时

php DateTime,带日期,不带小时,php,datetime,Php,Datetime,如何调整小时数以获得如下DateTime对象: new \DateTime(); /* DateTime Object ( [date] => 2016-04-20 04:45:24.000000 [timezone_type] => 3 [timezone] => UTC ) */ 我知道的唯一方法是: /* DateTime Object ( [date] => 2016-04-20 00:00:00.000000 [ti

如何调整小时数以获得如下DateTime对象:

new \DateTime();
/*
DateTime Object
(
    [date] => 2016-04-20 04:45:24.000000
    [timezone_type] => 3
    [timezone] => UTC
)
*/  
我知道的唯一方法是:

/*
DateTime Object
(
    [date] => 2016-04-20 00:00:00.000000
    [timezone_type] => 3
    [timezone] => UTC
)
*/

但是我不喜欢这个解决方案。

为构造函数设置参数

$date = new \DateTime();
$date->format('Y-m-d');
$date = new \DateTime($date->format('Y-m-d'));
UPD:如果对象在任何时间都已存在

$d = new \DateTime("midnight");
结果

$d->settime(0,0);

延长约会时间以获得舒适感

DateTime Object
(
    [date] => 2016-04-20 00:00:00.000000
    [timezone_type] => 3
    [timezone] => UTC
)
所以

$d=new DT();
echo$d->date;

echo$d->days2('2018-10-21')

遗憾的是,PHP没有一个本机类来处理没有时间的日期。 由于Doctrine和许多其他库都使用DateTime,所以我发现最好的方法就是使用helper类创建时间设置为0的DateTime对象

 class DT extends \DateTime {

  static function __diff($dt1, $dt2 = NULL){
    $a = gettype($dt1) === "string" ? new DateTime($dt1) :$dt1;
    $b = gettype($dt2) === "string" ? new DateTime($dt2) :$dt2 ?? new DateTime();
    return $a->diff($b);
    }

  public function __get($name) { // sql format
    switch ($name) {
        case "date":
            return $this->format("Y-m-d");
        case "time":
            return $this->format("H:i:s");
        case "datetime":
            return $this->date." ".$this->time;
        default:
            return $this->$name;
      }
  }

  public function days2($date){
    $to = gettype($date) === "string" ? new \DateTime($date):$date;
    return (int)$this->__diff($this->date,$to)->format('%R%a'); 
  }
}

对于那些喜欢以尽可能短的方式做事的人来说,这里有一行代码,用于获取当前日期或将字符串日期解析为DateTime对象,同时将小时、分钟和秒设置为0

今日:

$dateObj=新日期时间(“今天”);
对于特定日期:

$dateObj=新日期时间(“2019-02-12”)//时间部分将为0
要分析特定日期格式,请执行以下操作:

$dateObj=DateTime::createFromFormat(“!Y-m-d”,“2019-02-12”)//注意!

但是如果我已经有了date-DateTime('2016-04-20 04:45:24.000000'),我该怎么办?@SergeyOnishchenko
setTime()
是的,你是对的。话虽如此,我需要有两个对象的差异,一个来自某个日期,另一个来自当前时间,但不考虑小时数。可能重复的
class DateFactory
{
    public static function createOnlyDateFromFormat(string $format, string $value): \DateTime
    {
        $date = \DateTime::createFromFormat($format, $value);
        $date->setTime(0, 0, 0);

        return $date;
    }
}