是否有一个PHP函数,返回日期和时间在相同的格式MySQL函数NOW()?
我知道如何使用date()来做到这一点,但我在问是否有一个函数仅用于此。
例如,返回:
2009-12-01 00:00:00
是否有一个PHP函数,返回日期和时间在相同的格式MySQL函数NOW()?
我知道如何使用date()来做到这一点,但我在问是否有一个函数仅用于此。
例如,返回:
2009-12-01 00:00:00
当前回答
使用 strftime:
strftime("%F %T");
%F等于%Y-%m-%d。 %T与%H:%M:%S相同。
这是ideone上的一个演示。
其他回答
不久
echo date('Y-m-d H:i:s');
php高级现在类额外的addMinute addYear,如addHour等…
<?php /** @noinspection PhpUnhandledExceptionInspection */
/**
* Class Now
* @author dılo sürücü <berxudar@gmail.com>
*/
class Now
{
/**
* @var DateTime
*/
private $dateTime;
/**
* Now constructor.
* @throws Exception
*/
public function __construct()
{
$this->dateTime = new DateTime('now');
}
/**
* @param int $year
* @return Now
* @throws Exception
* @noinspection PhpUnused
*/
public function addYear(int $year): self
{
$this->dateTime->add(new DateInterval('P' . $year . 'Y'));
return $this;
}
/**
* @noinspection PhpUnused
* @param int $month
* @return Now
* @throws Exception
* @noinspection PhpUnused
*/
public function addMonth(int $month):self
{
$this->dateTime->add(new DateInterval('P' . $month . 'M'));
return $this;
}
/**
* @param int $day
* @return $this
* @throws Exception
*/
public function addDay(int $day): self
{
$this->dateTime->add(new DateInterval('P' . $day . 'D'));
return $this;
}
/**
* @noinspection PhpUnused
* @param int $week
* @return $this
* @throws Exception
*/
public function addWeek(int $week): self
{
return $this->addDay($week * 7);
}
/**
* @noinspection PhpUnused
* @param int $second
* @return $this
* @throws Exception
*/
public function addSecond(int $second): self
{
$this->dateTime->add(new DateInterval('PT' . $second . 'S'));
return $this;
}
/**
* @param int $minute
* @return $this
* @throws Exception
*/
public function addMinute(int $minute): self
{
$this->dateTime->add(new DateInterval('PT' . $minute . 'M'));
return $this;
}
/**
* @param int $hour
* @return $this
* @throws Exception
*/
public function addHour(int $hour): self
{
$this->dateTime->add(new DateInterval('PT' . $hour . 'H'));
return $this;
}
/**
* @return string
*/
public function get(): string
{
return $this->dateTime->format('Y-m-d H:i:s');
}
/**
* @return string
*/
public function __toString()
{
return $this->get();
}
}
/**
* @return Now
* @throws Exception
*/
function now()
{
return new Now();
}
使用
echo now(); //2020-03-10 22:10
echo now()->addDay(1); //2020-03-11 22:10
echo now()->addDay(1)->addHour(1); // //2020-03-11 23:10
echo now()->addDay(1)->addHour(1)->addMinute(30); // //2020-03-11 23:40
echo now()->addDay(1)->addHour(1)->addMinute(30)->addSecond(10); // //2020-03-11 23:50
//or u can use get method for example
echo now()->addDay(1)->addHour(1)->addMinute(30)->get(); // //2020-03-11 23:40
你可以使用date函数:
date("Y-m-d H:i:s");
MySQL函数NOW()返回当前时间戳。我发现PHP的唯一方法是使用下面的代码。
$curr_timestamp = date('Y-m-d H:i:s');
使用 strftime:
strftime("%F %T");
%F等于%Y-%m-%d。 %T与%H:%M:%S相同。
这是ideone上的一个演示。
使用PHP版本>= 5.4 DateTime可以做到这一点
echo (new \DateTime())->format('Y-m-d H:i:s');
看到它起作用了。