- date_create
- Список параметров
- Возвращаемые значения
- Ошибки
- Список изменений
- Примеры
- Смотрите также
- PHP DateTime
- Introduction to the PHP DateTime class
- Creating a DateTime object from a string
- Comparing two DateTime objects
- Calculating the differences between two DateTime objects
- Adding an interval to a DateTime object
- Summary
- How to Get Current Datetime (NOW) with PHP
- Example using date
- Example using datetime class
- A more complete approach
date_create
Создает и возвращает новый экземпляр класса DateTime.
Список параметров
Строка даты/времени. Объяснение корректных форматов дано в Форматы даты и времени.
Если используется аргумент $timezone , то для получения текущего времени в новом объекте достаточно передать NULL в качестве этого аргумента.
Объект класса DateTimeZone представляющий временную зону параметра $time .
Если аргумент $timezone не задан, будет использована текущая временная зона.
Замечание:
Значение аргумента $timezone равно как и текущая временная зона не будут учитываться, если в качестве аргумента $time передается метка времени UNIX (например @946684800) или время, в котором временная зона уже содержится (например 2010-01-28T15:00:00+02:00).
Возвращаемые значения
Возвращает созданный объект класса DateTime. Процедурный стиль возвращает FALSE в случае возникновения ошибки.
Ошибки
В случае ошибки выбрасывает исключение Exception.
Список изменений
Версия | Описание |
---|---|
5.3.0 | В случае задания параметру time неверного формата даты/времени выбрасывается исключение. Раньше скрипт выдавал ошибку. |
Примеры
Пример #1 Пример использования DateTime::__construct()
try $date = new DateTime ( ‘2000-01-01’ );
> catch ( Exception $e ) echo $e -> getMessage ();
exit( 1 );
>
?php
$date = date_create ( ‘2000-01-01’ );
if (! $date ) $e = date_get_last_errors ();
foreach ( $e [ ‘errors’ ] as $error ) echo » $error \n» ;
>
exit( 1 );
>
?php
echo date_format ( $date , ‘Y-m-d’ );
?>
Результат выполнения данных примеров:
Пример #2 Хитрости при использовании DateTime::__construct()
// Дата/время во временной зоне Вашего компьютера.
$date = new DateTime ( ‘2000-01-01’ );
echo $date -> format ( ‘Y-m-d H:i:sP’ ) . «\n» ;
?php
// Дата/время в заданной временной зоне.
$date = new DateTime ( ‘2000-01-01’ , new DateTimeZone ( ‘Pacific/Nauru’ ));
echo $date -> format ( ‘Y-m-d H:i:sP’ ) . «\n» ;
// Текущие дата и время во временной зоне Вашего компьютера.
$date = new DateTime ();
echo $date -> format ( ‘Y-m-d H:i:sP’ ) . «\n» ;
// Текущие дата и время в заданной временной зоне.
$date = new DateTime ( null , new DateTimeZone ( ‘Pacific/Nauru’ ));
echo $date -> format ( ‘Y-m-d H:i:sP’ ) . «\n» ;
// Использование метки времени UNIX.
// Обратите внимание: результат во временной зоне UTC.
$date = new DateTime ( ‘@946684800’ );
echo $date -> format ( ‘Y-m-d H:i:sP’ ) . «\n» ;
// Несуществующие значения все равно обрабатываются.
$date = new DateTime ( ‘2000-02-30’ );
echo $date -> format ( ‘Y-m-d H:i:sP’ ) . «\n» ;
?>
Результатом выполнения данного примера будет что-то подобное:
2000-01-01 00:00:00-05:00 2000-01-01 00:00:00+12:00 2010-04-24 10:24:16-04:00 2010-04-25 02:24:16+12:00 2000-01-01 00:00:00+00:00 2000-03-01 00:00:00-05:00
Смотрите также
- DateTime::createFromFormat() — Создает и возвращает экземпляр класса DateTime, соответствующий заданному формату
- DateTimeZone::__construct() — Создает новый объект DateTimeZone
- Форматы даты и времени
- date.timezone ini настройка
- date_default_timezone_set() — Устанавливает временную зону по умолчанию для всех функций даты/времени в скрипте
- DateTime::getLastErrors() — Возвращает предупреждения и ошибки
- checkdate() — Проверяет корректность даты по григорианскому календарю
PHP DateTime
Summary: in this tutorial, you’ll learn how to work with the date and time in an object-oriented way.
Introduction to the PHP DateTime class
PHP provides a set of date and time classes that allow you to work with the date and time in an object-oriented way.
To create a new date and time object, you use the DateTime class. For example:
$datetime = new DateTime(); var_dump($datetime);
Code language: PHP (php)
object(DateTime)#1 (3) ["date"]=> string(26) "2021-07-15 06:30:40.294788" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/Berlin" >
Code language: PHP (php)
The DateTime object represents the current date and time in the timezone specified in the PHP configuration file ( php.ini )
To set a new timezone, you create a new DateTimeZone object and pass it to the setTimezone() method of the DateTime object:
$datetime = new DateTime(); $timezone = new DateTimeZone('America/Los_Angeles'); $datetime->setTimezone($timezone); var_dump($datetime);
Code language: PHP (php)
object(DateTime)#1 (3) ["date"]=> string(26) "2021-07-14 21:33:27.986925" ["timezone_type"]=> int(3) ["timezone"]=> string(19) "America/Los_Angeles" >
Code language: PHP (php)
In this example, we create a new DateTimeZone object and set it to «America/Los_Angeles» . To get valid timezones supported by PHP, check out the timezone list.
To format a DateTime object, you use the format() method. The format string parameters are the same as those you use for the date() function. For example:
$datetime = new DateTime(); echo $datetime->format('m/d/Y g:i A');
Code language: PHP (php)
07/15/2021 6:38 AM
Code language: PHP (php)
To set a specific date and time, you can pass a date & time string to the DateTime() constructor like this:
$datetime = new DateTime('12/31/2019 12:00 PM'); echo $datetime->format('m/d/Y g:i A');
Code language: PHP (php)
Or you can use the setDate() function to set a date:
$datetime = new DateTime(); $datetime->setDate(2020, 5, 1); echo $datetime->format('m/d/Y g:i A');
Code language: PHP (php)
05/01/2020 6:42 AM
Code language: PHP (php)
The time is derived from the current time. To set the time, you use the setTime() function:
$datetime = new DateTime(); $datetime->setDate(2020, 5, 1); $datetime->setTime(5, 30, 0); echo $datetime->format('m/d/Y g:i A');
Code language: PHP (php)
05/01/2020 5:30 AM
Code language: PHP (php)
Since the setDate() , setTime() , and setTimeZone() method returns the DateTime object, you can chain them like this which is quite convenient.
$datetime = new DateTime(); echo $datetime->setDate(2020, 5, 1) ->setTime(5, 30) ->setTimezone(new DateTimeZone('America/New_York')) ->format('m/d/Y g:i A');
Code language: PHP (php)
04/30/2020 11:30 PM
Code language: PHP (php)
Creating a DateTime object from a string
When you pass the date string ’06/08/2021′ to the DateTime() constructor or setDate() function, PHP interprets it as m/d/Y . For example:
$datetime = new DateTime('06/08/2021'); echo $datetime->format('F jS, Y');
Code language: PHP (php)
June 8th, 2021
Code language: PHP (php)
If you want to pass it as August 6th, 2021, you need to use the – or . instead of /. For example:
$datetime = new DateTime('06-08-2021'); echo $datetime->format('F jS, Y');
Code language: PHP (php)
August 6th, 2021
Code language: PHP (php)
However, if you want to parse the date string ’06/08/2021′ as d/m/Y, you need to replace the / with – or . manually:
$ds = '06/08/2021'; $datetime = new DateTime(str_replace('/', '-', $ds)); echo $datetime->format('F jS, Y');
Code language: PHP (php)
August 6th, 2021
Code language: PHP (php)
A better way to do it is to use the createFromFormat() static method of the DateTime object:
$ds = '06/08/2021'; $datetime = DateTime::createFromFormat('d/m/Y', $ds); echo $datetime->format('F jS, Y');
Code language: PHP (php)
In this example, we pass the date format as the first argument and the date string as the second argument.
Note that when you pass a date string without the time, the DateTime() constructor uses midnight time. However, the createFromFormat() method uses the current time.
Comparing two DateTime objects
PHP allows you to compare two DateTime objects using the comparison operators including >, >=, . For example:
$datetime1 = new DateTime('01/01/2021 10:00 AM'); $datetime2 = new DateTime('01/01/2021 09:00 AM'); var_dump($datetime1 < $datetime2); // false var_dump($datetime1 > $datetime2); // true var_dump($datetime1 == $datetime2); // false var_dump($datetime1 $datetime2); // 1
Code language: PHP (php)
Calculating the differences between two DateTime objects
The diff() method of the DateTime() object returns the difference between two DateTime() objects as a DateInterval object. For example:
$dob = new DateTime('01/01/1990'); $to_date = new DateTime('07/15/2021'); $age = $to_date->diff($dob); var_dump($age);
Code language: PHP (php)
object(DateInterval)#3 (16) ["y"]=> int(31) ["m"]=> int(6) ["d"]=> int(14) ["h"]=> int(0) ["i"]=> int(0) ["s"]=> int(0) ["f"]=> float(0) ["weekday"]=> int(0) ["weekday_behavior"]=> int(0) ["first_last_day_of"]=> int(0) ["invert"]=> int(1) ["days"]=> int(11518) ["special_type"]=> int(0) ["special_amount"]=> int(0) ["have_weekday_relative"]=> int(0) ["have_special_relative"]=> int(0) >
Code language: PHP (php)
The DateInterval represents the differences between two dates in the year, month, day, hour, etc. To format the difference, you use the DateInterval ‘s format. For example:
$dob = new DateTime('01/01/1990'); $to_date = new DateTime('07/15/2021'); echo $to_date->diff($dob)->format('%Y years, %m months, %d days');
Code language: PHP (php)
31 years, 6 months, 14 days
Code language: PHP (php)
Adding an interval to a DateTime object
To add an interval to date, you create a new DateInterval object and pass it to the add() method. The following example adds 1 year 2 months to the date 01/01/2021 :
$datetime = new DateTime('01/01/2021'); $datetime->add(new DateInterval('P1Y2M')); echo $datetime->format('m/d/Y');
Code language: PHP (php)
03/01/2022
Code language: PHP (php)
To format a date interval, you use the date interval format strings.
To subtract an interval from a DateTime object, you create a negative interval and use the add() method.
Summary
- Use the DateTime class to work with the date and time.
- Use the DateTimeZone class to work with time zones.
- Use the comparison operators to compare two DateTime objects.
- Use the diff() method to calculate the difference between to DateTime objects.
- Use the DateInterval class to represent a date and time interval.
- Use the add() method to add an interval to or subtract an interval from a DateTime object.
How to Get Current Datetime (NOW) with PHP
Various date format expressions are available here.
Example using date
This expression will return NOW in format Y-m-d H:i:s
Example using datetime class
This expression will return NOW in format Y-m-d H:i:s
A more complete approach
Above examples will return NOW using your server timezone, as it is defined in php.ini , for example:
[Date] ; Defines the default timezone used by the date functions ; http://php.net/date.timezone date.timezone = Europe/Athens
But, the best approach is to save dates to UTC. UTC (also called Zulu time) is the standard international time. All time zones are expressed as offsets of UTC. Especially, if your application users are located in different timezones. Using php DateTime class it is easy to compute the time in user timezone from UTC, and you don’t have to worry about for Daylight Savings Time changes.
Define server timezone and server date format according to your preferences. My preferences are:
/* server timezone */ define('CONST_SERVER_TIMEZONE', 'UTC'); /* server dateformat */ define('CONST_SERVER_DATEFORMAT', 'YmdHis');
In this case, you may use the following simple function:
= 5.2 * * @param $str_user_timezone * @param string $str_server_timezone * @param string $str_server_dateformat * @return string */ function now($str_user_timezone, $str_server_timezone = CONST_SERVER_TIMEZONE, $str_server_dateformat = CONST_SERVER_DATEFORMAT) < // set timezone to user timezone date_default_timezone_set($str_user_timezone); $date = new DateTime('now'); $date->setTimezone(new DateTimeZone($str_server_timezone)); $str_server_now = $date->format($str_server_dateformat); // return timezone to server default date_default_timezone_set($str_server_timezone); return $str_server_now; > ?>
Entrepreneur | Full-stack developer | Founder of MediSign Ltd. I have over 15 years of professional experience designing and developing web applications. I am also very experienced in managing (web) projects.