📜  php datetime create - PHP (1)

📅  最后修改于: 2023-12-03 15:18:19.684000             🧑  作者: Mango

PHP DateTime Create

In PHP, the DateTime class allows you to work with date and time values easily. The create method is a convenient way to create DateTime objects.

Syntax
DateTime::create(string $time = "now", DateTimeZone $timezone = null): DateTime|false
  • $time: A string representing the date and time to be created. Defaults to "now".
  • $timezone: An optional DateTimeZone object representing the timezone to be used. Defaults to null.
Examples
Creating a DateTime object for the current time
$now = DateTime::create();
echo $now->format('Y-m-d H:i:s'); // outputs something like "2022-01-01 12:34:56"
Creating a DateTime object for a specific date and time
$datetime = DateTime::create('2022-01-01 12:34:56');
echo $datetime->format('Y-m-d H:i:s'); // outputs "2022-01-01 12:34:56"
Creating a DateTime object with a specific timezone
$datetime = DateTime::create('now', new DateTimeZone('America/Los_Angeles'));
echo $datetime->format('Y-m-d H:i:s'); // outputs something like "2022-01-01 09:34:56"
echo $datetime->getTimezone()->getName(); // outputs "America/Los_Angeles"
Conclusion

The create method of the DateTime class provides a simple yet powerful way to create date and time objects in PHP. Whether you need to work with the current date and time or a specific one, with or without a timezone, create has got you covered.