Date and Time

Nette\Utils\DateTime is a class extends native DateTime.

Installation:

composer require nette/utils

All examples assume the following class alias is defined:

use Nette\Utils\DateTime;

static from (string|int|\DateTimeInterface $time): DateTime

Creates a DateTime object from a string, UNIX timestamp, or other DateTimeInterface object. Throws an Exception if the date and time are not valid.

DateTime::from(1138013640); // creates a DateTime from the UNIX timestamp with a default timezamp
DateTime::from(42); // creates a DateTime from the current time plus 42 seconds
DateTime::from('1994-02-26 04:15:32'); // creates a DateTime based on a string
DateTime::from('1994-02-26'); // create DateTime by date, time will be 00:00:00

static fromParts (int $year, int $month, int $day, int $hour=0, int $minute=0, float $second=0.0): DateTime

Creates DateTime object or throws an Nette\InvalidArgumentException exception if the date and time are not valid.

DateTime::fromParts(1994, 2, 26, 4, 15, 32);

static createFromFormat (string $format, string $time, ?string|\DateTimeZone $timezone=null): DateTime|false

Extends DateTime::createFromFormat() with the ability to specify a timezone as a string.

DateTime::createFromFormat('d.m.Y', '26.02.1994', 'Europe/London'); // create with custom timezone

modifyClone (string $modify='')static

Creates a copy with a modified time.

$original = DateTime::from('2017-02-03');
$clone = $original->modifyClone('+1 day');
$original->format('Y-m-d'); // '2017-02-03'
$clone->format('Y-m-d');    // '2017-02-04'

__toString(): string

Returns the date and time in the format Y-m-d H:i:s.

echo $dateTime; // '2017-02-03 04:15:32'

Implements JsonSerializable

Returns the date and time in ISO 8601 format, which is used in JavaScript, for example.

$date = DateTime::from('2017-02-03');
echo json_encode($date);
version: 4.0 3.x 2.x