- Работа с датой в Битрикс
- Отмотать дату
- Начало месяца и начало квартала
- Работа с датой и временем
- Методы, используемые в SQL запросах
- Конвертация форматов
- Дополнительные функции
- Пользовательские комментарии
- Working with dates in php in Bitrix and not only
- The last notes
- Class connection
- Bitrix displays the date in the format «November 3»
- Get date format settings from admin. parts
- Creating an object of class \Bitrix\Main\Type\DateTime
- Create an object of class \ Bitrix \ Main \ Type \ DateTime from the current time
- Creating an object of the class \ Bitrix \ Main \ Type \ DateTime from a custom format
- Creating an object of class \ Bitrix \ Main \ Type \ DateTime from an arbitrary format with an indication of the time zone
- Creating an object of class \ Bitrix \ Main \ Type \ DateTime from timestamp
- Creating an object of class \ Bitrix \ Main \ Type \ DateTime from
- Creating an object of class \ Bitrix \ Main \ Type \ DateTime from a text string
- Get the time in the current site format
- Get time in unix timestamp
- Get time in any format
- Get the current timezone
- Checking for the object \ Bitrix \ Main \ Type \ DateTime or \Bitrix\Main\Type\Date
- Adding and subtracting dates using human readable format:
- Convert time format from bitrix format to php format:
- Checking if the date is correct:
- Parse the date \ time object into components
- Difference between dates in days \ hours \ minutes
- Convert the timestamp to the usual format
- Subtract / add month / day to date, etc.
- Memo on accepted date format standards in different countries
- Comments
- Leave a comment
- FEEDBACK
- Email me
- Phones
- Address
- Favorites
Работа с датой в Битрикс
Возможно, что битрикс хранит дату записи в одной зоне, а текущее время new DateTime() — в другой. Поэтому разница только что созданной записи и текущего времени таким образом может быть не равна нулю!
Округление идет в меньшую сторону, т.е. разница в 23 часа 59 мин 59 сек = 0 дней. Можно сказать, что если $date->diff($now)->format(‘%a’) >= 1 , прошло минимум 24 часа.
Точное значение в годах, месяцах, днях, часах, минутах и секундах:
die(var_dump( $date->diff($now)->format('%Y-%M-%D %H:%I:%S') ));
Разница в секундах — именно не по секундам, а общая в секундах:
$diff = $now->getTimestamp() - $date->getTimestamp();
Отмотать дату
Отмотать дату на начало предыдущего дня ( $numDays = 1 ) или позавчера ( $numDays = 2 ), причем с округлением до полуночи:
$now = new DateTime('now'); $intervalStart = clone $now; $intervalStart->modify(sprintf('-%s day', $numDays))->setTime(0, 0, 0); // 2016-05-04 00:00:00
Начало месяца и начало квартала
Дата начала месяца и квартала для текущей даты.
$monthDate = new DateTime(); // текущая дата $curDay = $monthDate->format('j'); $curMonth = $monthDate->format('n'); $curQuarter = ceil($curMonth / 3); // номер текущего квартала $quarterDeltaMonth = ($curMonth - 1) % 3; if($curDay != 1) { $monthDate->modify(sprintf('-%d day', $curDay - 1)); // начало месяца } $quarterDate = clone $monthDate; $quarterDate->modify(sprintf('-%d month', $quarterDeltaMonth)); // начало квартала
Работа с датой и временем
Вся работа с датами через API (вставки, выборки, фильтры и т.п.) производится в формате текущего сайта или, если в администартивной части, в формате текущего языка.
Для работы с датой и временем используются следующие функции:
- CDatabase::CharToDateFunction
- CDatabase::DateToCharFunction
- CDatabase::CurrentDateFunction
- CDatabase::CurrentTimeFunction
- CDataBase::DateFormatToPHP
- CDataBase::DatetimeToTimestampFunction
- CDataBase::FormatDate
- ConvertDateTime
- MakeTimeStamp
- ConvertTimeStamp
- CDataBase::IsDate
- CDataBase::CompareDates
- AddToTimeStamp
- ParseDateTime
- getmicrotime
- GetTimeFormat
- GetDateFormat
При задании формата даты и времени используются следующие обозначения:
С версии 11.5.4 главного модуля включена поддержка 12-часового формата времени и некоторые новые отображения месяца:
- MMMM — полный месяц (использовать только для вывода);
- M — первые 3 буквы месяца;
- G — час от 1-12 (без ведущего нуля);
- GG — 0-23 (без ведущего нуля);
- H — 01-12;
- HH — 00-23;
- TT — отображением AM/PM (верхний регистр);
- T — am/pm.
Методы, используемые в SQL запросах
$DB->CharToDateFunction("10.01.2003 23:59:59")." "; $rs = $DB->Query($strSql, false, $err_mess.__LINE__); ?>
$DB->DateToCharFunction("DATE_CREATE")." DATE_CREATE FROM my_table "; $rs = $DB->Query($strSql, false, $err_mess.__LINE__); ?>
$DB->CurrentDateFunction() "; $rs = $DB->Query($strSql, false, $err_mess.__LINE__); ?>
$DB->CurrentTimeFunction()." WHERE "; $Query($strSql, false, "FILE: ".__FILE__."
LINE: ".__LINE__); ?>
DatetimeToTimestampFunction("DATE_CREATE")." DATE_CREATE FROM my_table "; $rs = $DB->Query($strSql, false, $err_mess.__LINE__); ?>
Конвертация форматов
$DB->DateFormatToPHP("DD.MM.YYYY HH:MI:SS"); // d.m.Y H:i:s ?>
$DB->FormatDate("31.12.2005", "DD.MM.YYYY", "YYYY-MM-DD"); // 2005-12-31 ?>
Дополнительные функции
$DB->IsDate("12.10.2005 22:34:15", "DD.MM.YYYY HH:MI:SS") ? "OK" : "ERROR"; // OK echo $DB->IsDate("12.13.2005 22:34:15", "DD.MM.YYYY HH:MI:SS") ? "OK" : "ERROR"; // ERROR echo $DB->IsDate("12.13..2005 ABS", "DD.MM.YYYY HH:MI:SS") ? "OK" : "ERROR"; // ERROR ?>
$DB->CompareDates("01.01.2005", "01.01.2006"); // -1 echo $DB->CompareDates("01.01.2006", "01.01.2005"); // 1 echo $DB->CompareDates("01.01.2006", "01.01.2006"); // 0 ?>
AddToTimeStamp(array("DD" => -1, "MM" => 1), $stmp); // 1115454720 echo date("d.m.Y H:i:s", $stmp); // 06.05.2005 11:32:00 ?>
ParseDateTime("21.01.2004 23:44:15", "DD.MM.YYYY HH:MI:SS")) < echo "День: ".$arr["DD"]."
"; // День: 21 echo "Месяц: ".$arr["MM"]."
"; // Месяц: 1 echo "Год: ".$arr["YYYY"]."
"; // Год: 2004 echo "Часы: ".$arr["HH"]."
"; // Часы: 23 echo "Минуты: ".$arr["MI"]."
"; // Минуты: 44 echo "Секунды: ".$arr["SS"]."
"; // Секунды: 15 > else echo "Ошибка!"; ?>
DateFormatToPHP(CSite::GetDateFormat("SHORT")), time()); ?>
DateFormatToPHP( CSite::GetTimeFormat() ); ?>
Пользовательские комментарии
Мы будем рады, если разработчики добавят свои комментарии по практическому использованию методов системы.
Для этого нужно всего лишь авторизоваться на сайте
Но помните, что Пользовательские комментарии, несмотря на модерацию, не являются официальной документацией. Ответственность за их использование несет сам пользователь.
Также Пользовательские комментарии не являются местом для обсуждения функционала. По подобным вопросам обращайтесь на форумы.
В более поздней версии проблема с падежами решена. Пример использования:
$arParams["ACTIVE_DATE_FORMAT"]="j F Y"; // $arItem["PROPERTIES"]["DATE"]["VALUE"] - произвольное свойство типа дата CIBlockFormatProperties::DateFormat($arParams["ACTIVE_DATE_FORMAT"], MakeTimeStamp($arItem["PROPERTIES"]["DATE"]["VALUE"], CSite::GetDateFormat()));
По умолчанию дата выводится в формате 23 декабрь 2008 г., декабрь 23, 2008 г. ТО есть месяц — в именительном падеже. Если необходимо вывести дату в формате: 23 декабр(я) 2008 г., 15 ноябр(я) 2008 г., то:
function EditData ($DATA) // конвертирует формат даты с 04.11.2008 в 04 Ноября, 2008 < $MES = array( "01" =>«Января», «02» => «Февраля», «03» => «Марта», «04» => «Апреля», «05» => «Мая», «06» => «Июня», «07» => «Июля», «08» => «Августа», «09» => «Сентября», «10» => «Октября», «11» => «Ноября», «12» => «Декабря» ); $arData = explode(«.», $DATA); $d = ($arData[0]
Working with dates in php in Bitrix and not only
By contacting me you will receive a reliable and knowledgeable contractor who will quickly and efficiently implement any task for you and your business.
The last notes
On D7, work with date / time is carried out using the Bitrix \ Main \ Type \ Date and \Bitrix\Main\Type\DateTime classes
Class connection
use Bitrix \ Main \ Type \ DateTime;
Bitrix displays the date in the format «November 3»
strtolower(FormatDate("d F", MakeTimeStamp($arItem['ACTIVE_FROM'])))
Get date format settings from admin. parts
\ Bitrix \ Main \ Type \ DateTime :: getFormat () // will return, for example, "Y-m-d H: i: s"
Creating an object of class \Bitrix\Main\Type\DateTime
new \ Bitrix \ Main \ Type \ DateTime ("04/01/2020 12:00:00");
Create an object of class \ Bitrix \ Main \ Type \ DateTime from the current time
new \ Bitrix \ Main \ Type \ DateTime (date ("d.m.Y H: i: s"));
Creating an object of the class \ Bitrix \ Main \ Type \ DateTime from a custom format
$ dateTime = new \ Bitrix \ Main \ Type \ DateTime ("2020-04-01 12:00:00", "Y-m-d H: i: s");
Creating an object of class \ Bitrix \ Main \ Type \ DateTime from an arbitrary format with an indication of the time zone
$ timeZone = new \ DateTimeZone ('Europe / Moscow'); // For Moscow new \ DateTimeZone ('Asia / Novosibirsk'); // For Novosibirsk $ dateTime = new \ Bitrix \ Main \ Type \ DateTime ("2020-04-01 12:00:00", "Y-m-d H: i: s", $ timeZone);
Creating an object of class \ Bitrix \ Main \ Type \ DateTime from timestamp
$ dateTime = \ Bitrix \ Main \ Type \ DateTime :: createFromTimestamp (1585742400);
Creating an object of class \ Bitrix \ Main \ Type \ DateTime from
$ phpDateTime = new DateTime ('2020-04-01'); $ dateTime = \ Bitrix \ Main \ Type \ DateTime :: createFromPhp ($ phpDateTime);
Creating an object of class \ Bitrix \ Main \ Type \ DateTime from a text string
$ dateTime = \ Bitrix \ Main \ Type \ Date :: createFromText ("yesterday morning");
Get the time in the current site format
Get time in unix timestamp
Get time in any format
$ dateTime-> format ("Y-m-d H: i: s")
Get the current timezone
Checking for the object \ Bitrix \ Main \ Type \ DateTime or \Bitrix\Main\Type\Date
if ($ dateTime instanceof \ Bitrix \ Main \ Type \ DateTime || $ dateTime instanceof \ Bitrix \ Main \ Type \ Date)
Adding and subtracting dates using human readable format:
$ dateTime-> add ("1 year + 3 months - 5 seconds");
Convert time format from bitrix format to php format:
\ Bitrix \ Main \ Type \ DateTime :: convertFormatToPhp ('YYYY-MM-DD HH-MI-SS') // "Y-m-d H-i-s"
Checking if the date is correct:
\ Bitrix \ Main \ Type \ DateTime :: isCorrect ("2018-06-14 02:20:00", "Y-m-d H: i: s")
Parse the date \ time object into components
$ datetime = "01/21/2004 23:44:15"; // Initial time $ format = "DD.MM.YYYY HH: MI: SS"; //Format if ($ arr = ParseDateTime ($ datetime, $ format)) < echo "Day:". $ arr ["DD"]; // Day: 21 echo "Month:". $ arr ["MM"]; // Month: 1 echo "Year:". $ arr ["YYYY"]; // Year: 2004 echo "Hours:". $ arr ["HH"]; // Hours: 23 echo "Minutes:". $ arr ["MI"]; // Minutes: 44 echo "Seconds:". $ arr ["SS"]; // Seconds: 15 >
Difference between dates in days \ hours \ minutes
function dateDiff ($ date1, $ date2) < $ time = new DateTime ($ date1); $ since_time = $ time->diff (new DateTime ($ date2)); $ result ['days'] = $ since_time-> days; $ result ['hours'] = $ since_time-> days * 24 + $ since_time-> h; $ result ['minutes'] = ($ since_time-> days * 24 * 60) + ($ since_time-> h * 60) + $ since_time-> i; return $ result; >
Convert the timestamp to the usual format
function timestampToDate ($ timestamp, $ format = "d.m.Y H: i: s")
Subtract / add month / day to date, etc.
function dateDecrementByMonth ($ date_start)/ Subtract the month from the date return date ("d-m-Y", strtotime ("- 1 month", strtotime ($ date_start))); > function dateIncrementByMonth ($ date_start)/ Add month to date return date ("d-m-Y", strtotime ("+ 1 month", strtotime ($ date_start))); >
Memo on accepted date format standards in different countries
Russia DD.MM.YYYY HH: MI: SS USA MM-DD-YYYY HH: MI: SS International English DD-MM-YYYY HH: MI: SS UK DD / MM / YYYY HH: MI: SS
Comments
Leave a comment
The site uses a comment pre-moderation system, so your message will be published only after approval by the moderator
FEEDBACK
Email me
Are you developing a new service, making improvements to the existing one and want to be better than your competitors? You have come to the right place. I offer you a comprehensive studio-level website development. From me you can order design, layout, programming, development of non-traditional functionality, implementation of communication between CMS, CRM and Data Analitics, as well as everything else related to sites, except for promotion.
Contact, I will always advise on all questions and help you find the most effective solution for your business. I am engaged in the creation of sites in Novosibirsk and in other regions of Russia, I also work with the CIS countries. You will be satisfied with our cooperation
Phones
Address
630106, Россия, г. Новосибирск
By submitting the form, you automatically confirm that you have read and accept the Privacy Policy site
Website development for me is not just a field of activity or a hobby, it has long been a way of life. I like to create thoughtful, effective, beautiful and convenient solutions that meet all customer requirements.
Favorites
By submitting the form, you automatically confirm that you have read and accept Privacy policy of site
An error occurred while sending the request. Please wait and try again after a while or call my phone number
In the near future, a confirmation will be sent to your email address with a link to activate the subscription. Please confirm it.