- date — функция PHP DateTime () не работает должным образом
- Решение
- Другие решения
- PHP DateTime () функция не работает должным образом
- 3 ответа
- PHP: проблема с timestamp в DateTime
- New datetime php не работает
- Datetime()
- Вывод форматированной даты
- Вывод отметки времени (timestamp)
- Изменение времени
- Изменение метки timestamp
- Установка часового пояса
- Как добавить дни к значению даты
- Сравнение двух дат
- Конвертация номера месяца и имени месяца
- Получаем количество недель в месяце
- Класс DateTime
- Введение
- Обзор классов
- Список изменений
- Содержание
- User Contributed Notes 26 notes
date — функция PHP DateTime () не работает должным образом
У меня есть приложение для Android, которое используется для хранения данных пользователей в базе данных MySQL с использованием PHP. Мне нужно сделать некоторые проверки в соответствии с датой. В базе данных MySQL есть предопределенная дата для каждого пользователя. Дата увеличивается на 1 день, когда пользователь вводит данные дважды за этот день. И когда дата превышает текущую дату, она показывает сообщение о том, что «пользователь уже представил данные за день».
Но что происходит, если «$ last_updated» (дата, которая меняется каждый раз) является текущей датой, то это не входит в условие if. Поэтому, если «$ last_updated» является сегодняшней датой, пользователь получает сообщение «пользователь уже отправил данные за день». Я попытался сделать эхо «$ n», и он дает текущую дату. Таким образом, он не должен переходить в условие if, потому что ($ last_updated == $ n). Но это происходит внутри условия if, когда ($ last_updated == $ n). Я не знаю, почему это происходит. Может кто-нибудь помочь мне с этим?
Решение
Ваша проблема в том, что, поскольку вы не храните время в базе данных, и когда вы сравниваете дату с текущим временем, которое включает время, текущее время всегда будет больше, чем дата, которую вы извлекаете из базы данных.
Время базы данных 2017-03-17 становится временем 2017-03-17 00:00:00 php.
Когда вы сгенерируете php сейчас, это будет 2017-03-17 xx: xx: xx, который всегда будет больше времени базы данных
Вы также можете использовать функцию DateTime-> diff ().
Другие решения
Вам нужно сравнить их как объекты .. Попробуйте что-то вроде этого ..
Я не уверен, правильно ли установлены часовые пояса на вашем сервере, но я уверен, что вы также можете выполнить одно из следующих действий …
Источник
PHP DateTime () функция не работает должным образом
У меня есть приложение для Android, которое используется для хранения данных пользователей в базе данных MySQL с использованием PHP. Мне нужно сделать некоторые проверки в соответствии с датой. В базе данных MySQL есть предопределенная дата для каждого пользователя. Дата увеличивается на 1 день, когда пользователь вводит данные дважды за этот день. И когда дата превышает текущую дату, она показывает сообщение о том, что «пользователь уже представил данные за день».
Но что происходит, если «$ last_updated» (дата, которая меняется каждый раз) является текущей датой, то это не входит в условие if. Поэтому, если «$ last_updated» является сегодняшней датой, пользователь получает сообщение «пользователь уже отправил данные за день». Я попытался сделать эхо «$ n», и он дает текущую дату. Таким образом, он не должен переходить в условие if, потому что ($ last_updated == $ n). Но это происходит внутри условия if, когда ($ last_updated == $ n). Я не знаю, почему это происходит. Может кто-нибудь помочь мне с этим?
3 ответа
Ваша проблема заключается в том, что, поскольку вы не храните время в базе данных, и когда вы сравниваете дату с текущим временем, которое включает время, текущее время всегда будет больше, чем дата, которую вы извлекаете из базы данных.
Время базы данных 2017-03-17 становится временем 2017-03-17 00:00:00 php.
Когда вы сгенерируете php сейчас, будет 2017-03-17 xx: xx: xx, который всегда будет больше времени базы данных
Вы также можете использовать функцию DateTime-> diff ().
Вам нужно сравнить их как объекты .. Попробуйте что-то вроде этого ..
Я не уверен, правильно ли установлены часовые пояса на вашем сервере, но я уверен, что вы также можете выполнить одно из следующих действий .
Источник
PHP: проблема с timestamp в DateTime
Многие разработчики на PHP используют объекты класса DateTime. Об удобствах его я писать не буду, тем более на Хабре уже была статья об этом классе, не об этом речь.
Все бы хорошо, да есть у данного класса проблемка, с которой я столкнулся только недавно.
Объект класса DateTime в PHP можно создать как стандартным методом:
$date = new DateTime ( «2009-01-21» );
так и функцией date_create, входящей в состав PHP начиная с версии 5.2.0:
$date = date_create ( «2009-01-21» );
Конструктор принимает как параметр строку, которая определяет дату и время, также это могут быть названия дней недели и куча других параметров, которые описаны в документации к функции strtotime. Еще есть возможность передавать в конструктор метку времени (timestamp), поместив ее после символа «@», к примеру, так:
$date = new DateTime ( «@1232488800» );
Именно с этим параметром и возникли некоторые непонятки.
Для вывода информации о конкретном объекте даты создадим следующую функцию:
function date_info ( DateTime $date ) <
echo «
» ;
echo «Timestamp: » . $date -> format ( «U» ). ‘ — ‘ . $date -> format ( «d/m/Y H:i:s» ). «
» ;
$tz = $date -> getTimezone ();
echo «Timezone: » . $tz -> getName (). » (Offset: » . $date -> getOffset (). » sec.)
» ;
>
В ней мы выводим на экран следующие сведения:
— метку времени
— саму дату и время
— временную зону
— смещение в секундах этой самой временной зоны
Создаем объекты даты и выводим информацию о нем
$date1 = new DateTime ( «2009-01-21 00:00:00» );
date_info ( $date1 );
получили
Timestamp: 1232488800 — 21/01/2009 00:00:00
Timezone: Europe/Helsinki (Offset: 7200 sec.)
хорошо, у нас есть метка, дата и временная зона.
Создадим другой объект, передадим ему в параметр название недели того же дня — «Wednesday».
$date2 = new DateTime ( «Wednesday» );
date_info ( $date2 );
Так как это ближайшая среда, то дата будет той же
Timestamp: 1232488800 — 21/01/2009 00:00:00
Timezone: Europe/Helsinki (Offset: 7200 sec.)
Замечательно. Теперь у нас есть 2 одинаковые метки времени и совпадающие даты.
Теперь внимание, создаем объект с параметром временной метки и выводим информацию о нем
$date3 = new DateTime ( «@1232488800» );
date_info ( $date3 );
и что же мы видим:
Timestamp: 1232488800 — 20/01/2009 22:00:00
Timezone: Europe/Helsinki (Offset: 7200 sec.)
Метка времени осталась той же, временная зона тоже не поменялась, а вот дата и время сместились на время, соответствующие смещению временной зоны, только со знаком минус. То есть смещение как таковое у нас не сработало.
Я с недоумением смотрел на результат и не мог понять, как это возможно. Заново пересмотрел документацию — вроде все правильно сделал.
Решилось все, как обычно, методом научного тыка. Я подумал, а почему бы мне не применить к объекту его текущую временную зону
$date -> setTimezone (new DateTimeZone ( «Europe/Helsinki» ));
date_info ( $date );
и, О ЧУДО! Скрипт выдал мне нужную дату.
Timestamp: 1232488800 — 21/01/2009 00:00:00
Timezone: Europe/Helsinki (Offset: 7200 sec.)
Делал все эти телодвижения я в Виндовсе, стал уже грешить на нее, но попробовав в Линкусе, и получив тот же результат, кошусь в сторону разработчиков языка. Версия PHP в обеих ОСях 5.2.4, так что, возможно, в более новых версиях уже исправлено. Но кто предупрежден — тот вооружен.
Источник
New datetime php не работает
Начиная с версии 5.2 в PHP появился такой тип данных как DateTime. Попробуем в этой статье разобраться почему лучше использовать его вместо старых функций date() и time().
Функция date() используется для строкового отображения даты/времени. Функция принимает два параметра, 1-ый — формат возвращаемой строки, а второй — само значение даты. По умолчанию второй параметр принимает значение текущего момента времени, либо можно указать отметку времени в unix формате (timestamp).
Функция time() возвращает текущее время в unix формате (timestamp).
Datetime()
Объект Datetime впервые был представлен в PHP версии 5.2, он содержит в себе множество вспомогательных объектов, для решения проблем, с которыми вам приходилось сталкиваться при использовании функций date() и time(). Также был представлен объект DateTimeZone, который управляет часовым поясом, объект DateInterval соответствует интервалу времени (например 2 дня) от настоящего момента, DatePeriod показывает разницу во времени между двумя разными датами. Основное преимущество использования DateTime перед старыми функциями заключается в том, что значения дат проще изменять. Если вы хотите получить значение времени и даты при помощи функции date(), то вы напишите следующее:
А вот пример для установки часового пояса:
Проблема возникает при необходимости изменить или сравнить две отметки времени, DateTime имеет методы modify() и diff() упрощающие задачу. Преимущества DateTime проявляются когда вы манипулируете значениями дат.
Сначала объект надо инициализировать
Конструктор этого класса принимает два параметра. Первый — значение времени, вы можете использовать строку в формате функции date, время в формате Unix, интервал или период. Второй параметр — часовой пояс.
Вывод форматированной даты
Объект DateTime может работать также как и функция date, всего лишь необходимо вызвать метод format() указав формат возвращаемой строки.
Вывод отметки времени (timestamp)
Для вывода отметки времени в формате Unix существует метод getTimestamp() .
Изменение времени
Для изменения значения времени существует метод setTime() .
Изменение метки timestamp
Для этого придуман метод setTimestamp() .
Установка часового пояса
Второй параметр при создании объекта — DateTimeZone, он позволяет назначить часовой пояс нашему объекту. Это означает, что мы сможем легко сравнивать два значения времени из разных часовых поясов и получать корректную разницу.
Также для установки этого значения существует метод setTimezone() .
Полный список часовых поясов можно просмотреть на php.net.
Как добавить дни к значению даты
Для изменения значения даты в объекте DateTime можно использовать метод modify(). Он принимает в качестве параметра строковое значение дней, месяцев, года. Например, если хотите прибавить несколько дней, например 3 дня, один месяц и один год:
Сравнение двух дат
Код выше даст нам разницу двух дат в виде DateInterval.
Конвертация номера месяца и имени месяца
Довольно часто приходится получать имя месяца из его порядкового номера, для этого всего лишь нужно указать формат “F” в качестве первого параметра
При использовании класса DateTime можно применить метод format() .
Получаем количество недель в месяце
Следующий пример поможет вам получить количество недель в определенном месяце года.
Источник
Класс DateTime
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
Введение
Класс ведёт себя так же, как и DateTimeImmutable , за исключением того, что объекты модифицируются сами при вызове таких методов модификации, как DateTime::modify() .
Обзор классов
Список изменений
| Версия | Описание |
|---|---|
| 7.2.0 | Константы класса теперь DateTime определены в DateTimeInterface . |
Содержание
- DateTime::add — Добавляет заданное количество дней, месяцев, лет, часов, минут и секунд к объекту DateTime
- DateTime::__construct — Конструктор класса DateTime
- DateTime::createFromFormat — Разбирает строку с датой согласно указанному формату
- DateTime::createFromImmutable — Возвращает объект DateTime инкапсулирующий заданный объект DateTimeImmutable
- DateTime::createFromInterface — Возвращает новый объект DateTime, созданный из переданного объекта, реализующего интерфейс DateTimeInterface
- DateTime::getLastErrors — Возвращает предупреждения и ошибки
- DateTime::modify — Изменение временной метки
- DateTime::__set_state — Обработчик __set_state
- DateTime::setDate — Устанавливает дату
- DateTime::setISODate — Устанавливает дату в формате ISO
- DateTime::setTime — Устанавливает время
- DateTime::setTimestamp — Устанавливает дату и время на основе метки времени Unix
- DateTime::setTimezone — Устанавливает часовой пояс для объекта класса DateTime
- DateTime::sub — Вычитает заданное количество дней, месяцев, лет, часов, минут и секунд из времени объекта DateTime
User Contributed Notes 26 notes
DateTime supports microseconds since 5.2.2. This is mentioned in the documentation for the date function, but bears repeating here. You can create a DateTime with fractional seconds and retrieve that value using the ‘u’ format string.
// Instantiate a DateTime with microseconds.
$d = new DateTime ( ‘2011-01-01T15:03:01.012345Z’ );
// Output the microseconds.
echo $d -> format ( ‘u’ ); // 012345
// Output the date with microseconds.
echo $d -> format ( ‘Y-m-d\TH:i:s.u’ ); // 2011-01-01T15:03:01.012345
There is a subtle difference between the following two statments which causes JavaScript’s Date object on iPhones to fail.
= new DateTime ( ‘NOW’ );
echo $objDateTime -> format ( ‘c’ ); // ISO8601 formated datetime
echo $objDateTime -> format ( DateTime :: ISO8601 ); // Another way to get an ISO8601 formatted string
/**
On my local machine this results in:
Both of these strings are valid ISO8601 datetime strings, but the latter is not accepted by the constructor of JavaScript’s date object on iPhone. (Possibly other browsers as well)
*/
?>
Our solution was to create the following constant on our DateHelper object.
class DateHelper
<
/**
* An ISO8601 format string for PHP’s date functions that’s compatible with JavaScript’s Date’s constructor method
* Example: 2013-04-12T16:40:00-04:00
*
* PHP’s ISO8601 constant doesn’t add the colon to the timezone offset which is required for iPhone
**/
const ISO8601 = ‘Y-m-d\TH:i:sP’ ;
>
?>
Small but powerful extension to DateTime
class Blar_DateTime extends DateTime <
/**
* Return Date in ISO8601 format
*
* @return String
*/
public function __toString () <
return $this -> format ( ‘Y-m-d H:i’ );
>
/**
* Return difference between $this and $now
*
* @param Datetime|String $now
* @return DateInterval
*/
public function diff ( $now = ‘NOW’ ) <
if(!( $now instanceOf DateTime )) <
$now = new DateTime ( $now );
>
return parent :: diff ( $now );
>
/**
* Return Age in Years
*
* @param Datetime|String $now
* @return Integer
*/
public function getAge ( $now = ‘NOW’ ) <
return $this -> diff ( $now )-> format ( ‘%y’ );
>
= new Blar_DateTime ( ‘1879-03-14’ );
// Example 1
echo $birthday ;
// Result: 1879-03-14 00:00
Albert Einstein would now be ‘ , $birthday -> getAge (), ‘ years old.
Albert Einstein would now be 130 years old.
Albert Einstein would now be ‘ , $birthday -> diff ()-> format ( ‘%y Years, %m Months, %d Days’ ), ‘ old.
Albert Einstein would now be 130 Years, 10 Months, 10 Days old.
Albert Einstein was on 2010-10-10 ‘ , $birthday -> getAge ( ‘2010-10-10’ ), ‘ years old.
Albert Einstein was on 2010-10-10 131 years old.
Set Timezone and formatting.
= time ();
$timeZone = new \ DateTimeZone ( ‘Asia/Tokyo’ );
$time = new \ DateTime ();
$time -> setTimestamp ( $unixTime )-> setTimezone ( $timeZone );
$formattedTime = $time -> format ( ‘Y/m/d H:i:s’ );
echo $formattedTime ;
Example displaying each time format:
$dateTime = new DateTime();
foreach ([
‘ATOM’,
‘COOKIE’,
‘ISO8601’,
‘RFC822’,
‘RFC850’,
‘RFC1036’,
‘RFC1123’,
‘RFC2822’,
‘RFC3339’,
‘RFC3339_EXTENDED’,
‘RSS’,
‘W3C’,
] as $format) <
eval(«print ‘DateTimeInterface::$format\t’.\$dateTime->format(DateTimeInterface::$format).\»\n\»;»);
>
The above example will output:
DateTimeInterface::ATOM 2020-01-28T16:22:37-07:00
DateTimeInterface::COOKIE Tuesday, 28-Jan-2020 16:22:37 MST
DateTimeInterface::ISO8601 2020-01-28T16:22:37-0700
DateTimeInterface::RFC822 Tue, 28 Jan 20 16:22:37 -0700
DateTimeInterface::RFC850 Tuesday, 28-Jan-20 16:22:37 MST
DateTimeInterface::RFC1036 Tue, 28 Jan 20 16:22:37 -0700
DateTimeInterface::RFC1123 Tue, 28 Jan 2020 16:22:37 -0700
DateTimeInterface::RFC2822 Tue, 28 Jan 2020 16:22:37 -0700
DateTimeInterface::RFC3339 2020-01-28T16:22:37-07:00
DateTimeInterface::RFC3339_EXTENDED 2020-01-28T16:22:37.803-07:00
DateTimeInterface::RSS Tue, 28 Jan 2020 16:22:37 -0700
DateTimeInterface::W3C 2020-01-28T16:22:37-07:00
At PHP 7.1 the DateTime constructor incorporates microseconds when constructed from the current time. Make your comparisons carefully, since two DateTime objects constructed one after another are now more likely to have different values.
IF You want to create clone of $time, use clone..
= new DateTime ;
$clone = $now ; //this doesnot clone so:
$clone -> modify ( ‘-1 day’ );
echo $now -> format ( ‘d-m-Y’ ), «\n» , $clone -> format ( ‘d-m-Y’ );
echo ‘—-‘ , «\n» ;
// will print same.. if you want to clone make like this:
$now = new DateTime ;
$clone = clone $now ;
$clone -> modify ( ‘-1 day’ );
echo $now -> format ( ‘d-m-Y’ ), «\n» , $clone -> format ( ‘d-m-Y’ );
?>
Results:
18-07-2011
18-07-2011
—-
19-07-2011
18-07-2011
This caused some confusion with a blog I was working on and just wanted to make other people aware of this. If you use createFromFormat to turn a date into a timestamp it will include the current time. For example:
= DateTime :: createFromFormat ( ‘m/d/Y’ , ‘1/10/2014’ );
echo $publishDate -> getTimestamp ();
?>
Would not output the expected «1389312000» instead it would output something more like «1389344025». To fix this you would want to do:
= DateTime :: createFromFormat ( ‘m/d/Y’ , ‘1/10/2014’ );
$publishDate -> setTime ( 0 , 0 , 0 );
echo $publishDate -> getTimestamp ();
?>
I hope this helps someone!
if you’d like to print all the built-in formats,
foreach((new ReflectionClass ( ‘DateTime’ ))-> getConstants () as $name => $format ) <
echo ‘DateTime::’ . $name . ‘ -> ‘ . date ( $format ). PHP_EOL ;
>
This might be unexpected behavior:
= DateTime :: createFromFormat ( ‘Y-m-d H:i:s’ , ‘2017-08-31 00:00:00’ );
$date1 -> modify ( ‘+1 month’ );
#or use the interval
#$date1->add(new DateInterval(«P1M»));
#will produce 2017-10-1
#not 2017-09-30
If you have timezone information in the time string you construct the DateTime object with, you cannot add an extra timezone in the constructor. It will ignore the timezone information in the time string:
$date = new DateTime(«2010-07-05T06:00:00Z», new DateTimeZone(«Europe/Amsterdam»));
will create a DateTime object set to «2010-07-05 06:00:00+0200» (+2 being the TZ offset for Europe/Amsterdam)
To get this done, you will need to set the timezone separately:
$date = new DateTime(«2010-07-05T06:00:00Z»);
$date->setTimeZone(new DateTimeZone(«Europe/Amsterdam»);
This will create a DateTime object set to «2010-07-05 08:00:00+0200»
A good way I did to work with millisecond is transforming the time in milliseconds.
function timeToMilliseconds($time) <
$dateTime = new DateTime($time);
$seconds = 0;
$seconds += $dateTime->format(‘H’) * 3600;
$seconds += $dateTime->format(‘i’) * 60;
$seconds += $dateTime->format(‘s’);
$seconds = floatval($seconds . ‘.’ . $dateTime->format(‘u’));
return $seconds * 1000;
>
It isn’t obvious from the above, but you can insert a letter of the alphabet directly into the date string by escaping it with a backslash in the format string. Note that if you are using «double» speech marks around the format string, you will have to further escape each backslash with another backslash! If you are using ‘single’ speech marks around the format string, then you only need one backslash.
For instance, to create a string like «Y2014M01D29T1633», you *could* use string concatenation like so:
= «Y» . date ( «Y» , $when ) . «M» . date ( «m» , $when ) . «D» . date ( «d» , $when ) . «T» . date ( «Hi» , $when );
?>
but you could also escape the letters with backslashes like so:
= date ( ‘\YY\Mm\Dd\THi’ , $when );
$dtstring2 = date ( «\\YY\\Mm\\Dd\\THi» , $when );
?>
This method involves fewer function calls, so probably is slightly quicker; and also is immune to race conditions if you are not specifying the second argument. [It’s possible that you could evaluate date(«d») just *before* midnight and date(«H») just *after* midnight. This will not give you the result you were expecting.]
please note that using
setTimezone
setTimestamp
setDate
setTime
etc..
will modify the original object, and the return value is $this
$original = new DateTime(«now»);
$modified = $original->setTimezone(new DateTimezone(«europe/rome»));
echo $original === $modified ? «THE OBJECT IS THE SAME» : «OBJECTS ARE DIFFERENT»;
so a datetime object is mutable
(Editors note: PHP 5.5 adds DateTimeImmutable which does not modify the original object, instead creating a new instance.)
Create function to convert GregorianDate to JulianDayCount
function dateJulian ( $date ) <
$dateTime = new DateTime ( $date );
$limitDate = new DateTime ( ’01-03-‘ . $dateTime -> format ( ‘Y’ ));
$diff = $dateTime -> diff ( $limitDate );
$soma = 1 ;
if ( $dateTime -> format ( ‘L’ ) && $diff -> invert ) <
$soma = 2 ;
>
return ( (int) $dateTime -> format ( ‘z’ )) + $soma ;
>
echo PHP_EOL , dateJulian ( ’01-03-2015′ ), PHP_EOL ;
echo PHP_EOL , dateJulian ( ’01-03-2016′ ), PHP_EOL ;
Note that the ISO8601 constant will not correctly parse all possible ISO8601 compliant formats, as it does not support fractional seconds. If you need to be strictly compliant to that standard you will have to write your own format.
Bug report #51950 has unfortunately be closed as «not a bug» even though it’s a clear violation of the ISO8601 standard.
It seems like, due to changes in the DateTimeZone class in PHP 5.5, when creating a date and specifying the timezone as a a string like ‘EDT’, then getting the timezone from the date object and trying to use that to set the timezone on a date object you will have problems but never know it. Take the following code:
= new DateTime ( ‘2015-08-21 15:00:00 EDT’ ) ;
$tz_string = $date -> getTimezone ()-> getName () ;
$tz = new DateTimeZone ( $tz_string ) ;
$date -> setTimezone ( $tz ) ;
?>
You would think this code should not change $date at all, but it does. It seems like you can create a timezone object like ‘EDT’ but can’t use those to set timezones properly. The process, however does act like it’s working without errors.
Be aware that DateTime may ignore fractional seconds for some formats, but not when using the ISO 8601 time format, as documented by this bug:
$dateTime = DateTime::createFromFormat(
DateTime::ISO8601,
‘2009-04-16T12:07:23.596Z’
);
// bool(false)
/**
* @param str => $formato_final = formato de saída
*/
public function now ( string $formato_final = ‘Y-m-d H:i:s’ ) <
return (new DateTime ( ‘now’ ))-> format ( $formato_final );
>
/**
* @param str => $data = data a ser formatada
* @param str => $formato_final = formato de saída
*/
public function format ( string $data , string $formato_final ) <
return (new DateTime ( $data ))-> format ( $formato_final );
>
/**
* @param str => $data_inicio = data de inicio que recebe o acréscimo
* @param arr => $add = valores adicionados [ano,mes,dia,hora,minuto,segundo]
* @param str => $formato_final = formato de saída
*/
public function add ( string $data_inicio , array $add = [ 0 , 0 , 0 , 0 , 0 , 0 ], string $formato_final ) <
return (new DateTime ( $data_inicio ))-> add (new DateInterval ( ‘P’ . $add [ 0 ]. ‘Y’ . $add [ 1 ]. ‘M’ . $add [ 2 ]. ‘DT’ . $add [ 3 ]. ‘H’ . $add [ 4 ]. ‘M’ . $add [ 5 ]. ‘S’ ))-> format ( $formato_final );
>
/**
* @param str => $data_inicio = data de inicio que recebe o decréscimo
* @param arr => $add = valores adicionados [ano,mes,dia,hora,minuto,segundo]
* @param str => $formato_final = formato de saída
*/
public function sub ( string $data_inicio , array $add = [ 0 , 0 , 0 , 0 , 0 , 0 ], string $formato_final ) <
return (new DateTime ( $data_inicio ))-> sub (new DateInterval ( ‘P’ . $add [ 0 ]. ‘Y’ . $add [ 1 ]. ‘M’ . $add [ 2 ]. ‘DT’ . $add [ 3 ]. ‘H’ . $add [ 4 ]. ‘M’ . $add [ 5 ]. ‘S’ ))-> format ( $formato_final );
>
var_dump ((new DatetimeTool )-> format ( ‘1970-01-01’ , ‘d-m-Y’ ));
var_dump ((new DatetimeTool )-> add ( date ( ‘d-m-Y H:i:s’ ), [ 0 , 1 , 0 , 0 , 10 , 0 ], ‘d-m-Y’ ));
var_dump ((new DatetimeTool )-> sub ( date ( ‘d-m-Y H:i:s’ ), [ 0 , 1 , 0 , 0 , 10 , 0 ], ‘d-m-Y’ ));
Be aware of this behaviour:
= new \ DateTime ( ‘2014/12/31’ );
$dt1 -> modify ( ‘-1 month’ );
$m = (int) $dt1 -> format ( ‘m’ );
var_dump ( $m ); // still 12 .
$dt2 = new \ DateTime ( ‘2014/12/30’ );
$dt2 -> modify ( ‘-1 month’ );
$m = (int) $dt2 -> format ( ‘m’ );
var_dump ( $m ); // 11
?>
The method modify( ‘-1 month’ ) appear to remove 30 days, not to subtract 1 from the month and adjust the day (if needed).
In my opinion, the former date should be adjusted to 2014/11/30, that is, the last day in the previous month.
Here is easiest way to find the days difference between two dates:
if(! function_exists ( ‘date_between’ )) :
function date_between ( $date_start , $date_end )
<
if(! $date_start || ! $date_end ) return 0 ;
if( class_exists ( ‘DateTime’ ) )
<
$date_start = new DateTime ( $date_start );
$date_end = new DateTime ( $date_end );
return $date_end -> diff ( $date_start )-> format ( ‘%a’ );
>
else
<
return abs ( round ( ( strtotime ( $date_start ) — strtotime ( $date_end ) ) / 86400 ) );
>
>
endif;
?>
In the general, I use ‘DateTime’ to find days between 2 dates. But if in the some reason, some server setup not have ‘DateTime’ enabled, it will use simple (but not safe) calculation with ‘strtotime()’.
If you’re stuck on a PHP 5.1 system (unfortunately one of my clients is on a rather horrible webhost who claims they cannot upgrade php) you can use this as a quick workaround:
if (! class_exists ( ‘DateTime’ )) <
class DateTime <
public $date ;
public function __construct ( $date ) <
$this -> date = strtotime ( $date );
>
public function setTimeZone ( $timezone ) <
return;
>
private function __getDate () <
return date ( DATE_ATOM , $this -> date );
>
public function modify ( $multiplier ) <
$this -> date = strtotime ( $this -> __getDate () . ‘ ‘ . $multiplier );
>
public function format ( $format ) <
return date ( $format , $this -> date );
>
>
>
?>
it is NOT perfect. Timezones and DST are not supported, but if you just need compatible basic functions this works. Feel free to complete this so it’s compatible with the 5.2 datetime object.
If you need DateTime::createFromFormat functionality in versions class DateClass extends DateTime <
<>
public function getTimestamp () <
return $this -> format ( «U» );
>
/**
* This function calculates the number of days between the first and the second date. Arguments must be subclasses of DateTime
**/
static function differenceInDays ( $firstDate , $secondDate ) <
$firstDateTimeStamp = $firstDate -> format ( «U» );
$secondDateTimeStamp = $secondDate -> format ( «U» );
$rv = round ((( $firstDateTimeStamp — $secondDateTimeStamp ))/ 86400 );
return $rv ;
>
/**
* This function returns an object of DateClass from $time in format $format. See date() for possible values for $format
**/
static function createFromFormat ( $format , $time ) <
assert ( $format != «» );
if( $time == «» ) <
return new DateClass ();
>
$regexpArray [ ‘Y’ ] = «(?P 19|20\d\d)» ;
$regexpArray [ ‘m’ ] = «(?P 04|1[012])» ;
$regexpArray [ ‘d’ ] = «(?P 01|[12]8|3[01])» ;
$regexpArray [ ‘-‘ ] = «[-]» ;
$regexpArray [ ‘.’ ] = «[\. /.]» ;
$regexpArray [ ‘:’ ] = «[:]» ;
$regexpArray [ ‘space’ ] = «[\s]» ;
$regexpArray [ ‘H’ ] = «(?P 07|17|23)» ;
$regexpArray [ ‘i’ ] = «(?P23)» ;
$regexpArray [ ‘s’ ] = «(?P59)» ;
$formatArray = str_split ( $format );
$regex = «» ;
// create the regular expression
foreach( $formatArray as $character ) <
if ( $character == » » ) $regex = $regex . $regexpArray [ ‘space’ ];
elseif ( array_key_exists ( $character , $regexpArray )) $regex = $regex . $regexpArray [ $character ];
>
$regex = «/» . $regex . «/» ;
// get results for regualar expression
preg_match ( $regex , $time , $result );
// create the init string for the new DateTime
$initString = $result [ ‘Y’ ]. «-» . $result [ ‘m’ ]. «-» . $result [ ‘d’ ];
// if no value for hours, minutes and seconds was found add 00:00:00
if (isset( $result [ ‘H’ ])) $initString = $initString . » » . $result [ ‘H’ ]. «:» . $result [ ‘i’ ]. «:» . $result [ ‘s’ ];
else
$newDate = new DateClass ( $initString );
return $newDate ;
>
>
Источник