本文整理汇总了PHP中Bitrix\Main\Type\DateTime类的典型用法代码示例。如果您正苦于以下问题:PHP DateTime类的具体用法?PHP DateTime怎么用?PHP DateTime使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DateTime类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: onBeforeAdd
/**
* @param Entity\Event $event
* @return Entity\EventResult
*/
public static function onBeforeAdd(Entity\Event $event)
{
$result = new Entity\EventResult();
$data = $event->getParameter('fields');
if (isset($data['TOKEN_EXPIRES_IN'])) {
$dateTime = new Type\DateTime();
$dateTime->add('+ ' . $data['TOKEN_EXPIRES_IN'] . ' sec');
$result->modifyFields(['TOKEN_FINAL_DATE' => $dateTime]);
}
return $result;
}
示例2: getDateTimeToDbFunction
public function getDateTimeToDbFunction(\Bitrix\Main\Type\DateTime $value, $type = \Bitrix\Main\Type\DateTime::DATE_WITH_TIME)
{
$customOffset = $value->getOffset();
$serverTime = new \Bitrix\Main\Type\DateTime();
$serverOffset = $serverTime->getOffset();
$diff = $customOffset - $serverOffset;
$valueTmp = clone $value;
$valueTmp->sub(new \DateInterval(sprintf("PT%sS", $diff)));
$format = $type == \Bitrix\Main\Type\DateTime::DATE_WITHOUT_TIME ? "Y-m-d" : "Y-m-d H:i:s";
$date = "CONVERT(datetime, '" . $valueTmp->format($format) . "', 120)";
return $date;
}
示例3: convertTo
/**
* @param FieldType $fieldType Document field type.
* @param mixed $value Field value.
* @param string $toTypeClass Type class name.
* @return null|mixed
*/
public static function convertTo(FieldType $fieldType, $value, $toTypeClass)
{
/** @var Base $toTypeClass */
$type = $toTypeClass::getType();
switch ($type) {
case FieldType::BOOL:
$value = (bool) $value ? 'Y' : 'N';
break;
case FieldType::DATE:
$value = date(Main\Type\Date::convertFormatToPhp(\FORMAT_DATE), (int) $value);
break;
case FieldType::DATETIME:
$value = date(Main\Type\DateTime::convertFormatToPhp(\FORMAT_DATETIME), (int) $value);
break;
case FieldType::DOUBLE:
$value = (double) $value;
break;
case FieldType::INT:
$value = (int) $value;
break;
case FieldType::STRING:
case FieldType::TEXT:
$value = (string) $value;
break;
case FieldType::USER:
$value = 'user_' . (int) $value;
break;
default:
$value = null;
}
return $value;
}
示例4: convertTo
/**
* @param FieldType $fieldType Document field type.
* @param mixed $value Field value.
* @param string $toTypeClass Type class name.
* @return null|mixed
*/
public static function convertTo(FieldType $fieldType, $value, $toTypeClass)
{
/** @var Base $toTypeClass */
$type = $toTypeClass::getType();
switch ($type) {
case FieldType::DOUBLE:
case FieldType::INT:
$value = $value ? (int) strtotime($value) : 0;
break;
case FieldType::DATE:
$value = date(Type\Date::convertFormatToPhp(\FORMAT_DATE), strtotime($value));
break;
case FieldType::DATETIME:
$value = date(Type\DateTime::convertFormatToPhp(\FORMAT_DATETIME), strtotime($value));
break;
case FieldType::STRING:
case FieldType::TEXT:
$value = (string) $value;
if ($value) {
$format = static::getType() == FieldType::DATE ? \FORMAT_DATE : \FORMAT_DATETIME;
$value = date(Type\DateTime::convertFormatToPhp($format), strtotime($value));
}
break;
default:
$value = null;
}
return $value;
}
示例5: onGenerateInitialData
public static function onGenerateInitialData(Date $from, Date $to)
{
$data = array();
// 1. Payments
$result = \CSaleOrder::GetList(array(), array('PAYED' => 'Y', 'CANCELED' => 'N', '>=DATE_PAYED' => $from, '<=DATE_PAYED' => $to), false, false, array('LID', 'DATE_PAYED', 'PRICE', 'CURRENCY'));
while ($row = $result->Fetch()) {
$day = new DateTime($row['DATE_PAYED']);
$sum = Config::convertToBaseCurrency($row['PRICE'], $row['CURRENCY']);
if ($counters =& $data[$row['LID']][$day->format('Y-m-d')]) {
$counters['sale_payment_add_day'] += 1;
$counters['sale_payment_sum_add'] += $sum;
} else {
$counters = array('sale_payment_add_day' => 1, 'sale_payment_sum_add' => $sum);
}
}
// 2. Orders
$result = \CSaleOrder::GetList(array(), array('CANCELED' => 'N', '>=DATE_INSERT' => $from, '<=DATE_INSERT' => $to), false, false, array('LID', 'DATE_INSERT', 'PRICE', 'CURRENCY'));
while ($row = $result->Fetch()) {
$day = new DateTime($row['DATE_INSERT']);
$sum = Config::convertToBaseCurrency($row['PRICE'], $row['CURRENCY']);
if ($counters =& $data[$row['LID']][$day->format('Y-m-d')]) {
$counters['sale_order_add_day'] += 1;
$counters['sale_order_sum_add'] += $sum;
} else {
$counters = array('sale_order_add_day' => 1, 'sale_order_sum_add' => $sum);
}
}
// 3. Cart
$result = \CSaleBasket::GetList(array(), array('>=DATE_INSERT' => $from, '<=DATE_INSERT' => $to), false, false, array('LID', 'DATE_INSERT', 'PRICE', 'CURRENCY', 'QUANTITY'));
while ($row = $result->Fetch()) {
$day = new DateTime($row['DATE_INSERT']);
$sum = Config::convertToBaseCurrency($row['PRICE'] * $row['QUANTITY'], $row['CURRENCY']);
if ($counters =& $data[$row['LID']][$day->format('Y-m-d')]) {
$counters['sale_cart_add_day'] += 1;
$counters['sale_cart_sum_add'] += $sum;
} else {
$counters = array('sale_cart_add_day' => 1, 'sale_cart_sum_add' => $sum);
}
}
// Result
unset($counters);
$result = array();
foreach ($data as $siteId => $dayCounters) {
$result[] = array('ATTRIBUTES' => array('conversion_site' => $siteId), 'DAY_COUNTERS' => $dayCounters);
}
return $result;
}
示例6: passed
/**
* Возвращает дату в формате прошедшего времени. Например, "15 минут назад", "2 часа назад", "вчера", ...
* @param \Bitrix\Main\Type\DateTime $datetime
* @return string
*/
public static function passed(\Bitrix\Main\Type\DateTime $datetime, $formatDateTime = 'd.m.Y H:i', $formatDay = 'H:i')
{
$time = $datetime->getTimestamp();
$diff = time() - $time;
//
if (self::passedYesterday($time, $output)) {
return $output;
} elseif ($diff < 60) {
return "только что";
} elseif ($diff < 60 * 60) {
return self::passedMinutes(0, $diff);
} elseif ($diff < 60 * 60 * 24) {
return self::passedHours(0, $diff);
} else {
return $datetime->format($formatDateTime);
}
}
示例7: generateInitialData
public static function generateInitialData(Date $from)
{
if (($to = Option::get('conversion', 'START_DATE_TIME', 'undefined')) != 'undefined' && DateTime::isCorrect($to, 'Y-m-d H:i:s') && ($to = new DateTime($to, 'Y-m-d H:i:s')) && $to->format('Y-m-d H:i:s') > $from->format('Y-m-d H:i:s') && Option::get('conversion', 'GENERATE_INITIAL_DATA', 'undefined') == 'undefined') {
Option::set('conversion', 'GENERATE_INITIAL_DATA', 'generated');
$context = new self();
// generate data
$data = array();
foreach (EventManager::getInstance()->findEventHandlers('conversion', 'OnGenerateInitialData') as $handler) {
$result = ExecuteModuleEventEx($handler, array($from, $to));
// TODO validate
foreach ($result as $row) {
$context->id = null;
$context->attributes = array();
$context->setAttributes($row['ATTRIBUTES']);
$context->save();
if ($dayCounters =& $data[$context->id]) {
self::appendDayCounters($dayCounters, $row['DAY_COUNTERS']);
} else {
$dayCounters = $row['DAY_COUNTERS'];
}
}
}
unset($dayCounters);
// save data to database
$numerators = CounterManager::getTypes(array('GROUP' => 'day'));
unset($numerators['conversion_visit_day']);
foreach ($data as $id => $dayCounters) {
$context->id = $id;
foreach ($dayCounters as $day => $counters) {
$day = new Date($day, 'Y-m-d');
$visitSum = 0;
$visitQuantity = 0;
unset($counters['conversion_visit_day']);
foreach ($counters as $name => $value) {
$context->addCounter($day, $name, $value);
if ($numerators[$name]) {
$visitSum += $value;
$visitQuantity += 1;
}
}
$context->addCounter($day, 'conversion_visit_day', $visitQuantity ? round($visitSum / $visitQuantity * 100) + 1 : 1);
}
}
}
}
示例8: externalize
public function externalize()
{
$result = array('srcEntityTypeID' => $this->srcEntityTypeID, 'dstEntityTypeID' => $this->dstEntityTypeID, 'time' => $this->time->format(\DateTime::ISO8601), 'items' => array());
if ($this->srcIndex !== null) {
foreach ($this->srcIndex as $item) {
$result['items'][] = $item->externalize();
}
}
return $result;
}
示例9: modifyToDb
protected static function modifyToDb($data)
{
$result = array();
foreach ($data as $name => $value) {
if ($name == 'date' && $value instanceof \DateTime) {
$value = DateTime::createFromPhp($value);
}
if (in_array($name, array('originalData', 'updateData'))) {
$value = \WS\Migrations\arrayToJson($value);
}
$result[$name] = $value;
}
return $result;
}
示例10: convertTo
/**
* @param FieldType $fieldType Document field type.
* @param mixed $value Field value.
* @param string $toTypeClass Type class name.
* @return null|mixed
*/
public static function convertTo(FieldType $fieldType, $value, $toTypeClass)
{
/** @var Base $toTypeClass */
$type = $toTypeClass::getType();
switch ($type) {
case FieldType::BOOL:
$value = strtolower((string) $value);
$value = in_array($value, array('y', 'yes', 'true', '1')) ? 'Y' : 'N';
break;
case FieldType::DATE:
$value = date(Main\Type\Date::convertFormatToPhp(\FORMAT_DATE), strtotime($value));
break;
case FieldType::DATETIME:
$value = date(Main\Type\DateTime::convertFormatToPhp(\FORMAT_DATETIME), strtotime($value));
break;
case FieldType::DOUBLE:
$value = str_replace(' ', '', str_replace(',', '.', $value));
$value = (double) $value;
break;
case FieldType::INT:
$value = str_replace(' ', '', $value);
$value = (int) $value;
break;
case FieldType::STRING:
case FieldType::TEXT:
$value = (string) $value;
break;
case FieldType::USER:
$value = trim($value);
if (strpos($value, 'user_') === false && strpos($value, 'group_') === false && !preg_match('#^[0-9]+$#', $value)) {
$value = null;
}
break;
default:
$value = null;
}
return $value;
}
示例11: fixColdStart
/**
* Fixes cold start, when we don't have any data in RecentlyUsedTable.
* @param mixed|int|User|\CAllUser $user User.
* @return bool
* @throws \Bitrix\Main\ArgumentException
*/
private function fixColdStart($user)
{
$userId = User::resolveUserId($user);
if (!$userId) {
$this->errorCollection->addOne(new Error('Could not get user id.'));
return false;
}
$storage = Driver::getInstance()->getStorageByUserId($userId);
if (!$storage) {
$this->errorCollection->addOne(new Error('Could not get storage by user id.'));
return false;
}
$fromDate = DateTime::createFromTimestamp(time() - 14 * 24 * 3600);
$objects = array();
$query = FileTable::getList(array('select' => array('ID', 'UPDATE_TIME'), 'filter' => array('STORAGE_ID' => $storage->getId(), 'TYPE' => ObjectTable::TYPE_FILE, 'DELETED_TYPE' => ObjectTable::DELETED_TYPE_NONE, '>UPDATE_TIME' => $fromDate, array('LOGIC' => 'OR', array('CREATED_BY' => $userId), array('UPDATED_BY' => $userId))), 'order' => array('UPDATE_TIME' => 'DESC'), 'limit' => RecentlyUsedTable::MAX_COUNT_FOR_USER));
while ($row = $query->fetch()) {
$objects[] = array('USER_ID' => $userId, 'OBJECT_ID' => $row['ID'], 'CREATE_TIME' => $row['UPDATE_TIME']);
}
unset($row, $query, $fromDate);
Collection::sortByColumn($objects, array('CREATE_TIME' => SORT_ASC));
RecentlyUsedTable::insertBatch($objects);
return true;
}
示例12: getHourlyCompanyActivitySince
protected static function getHourlyCompanyActivitySince(Type\DateTime $hour = null)
{
$query = new Entity\Query('Bitrix\\Intranet\\UStat\\UserHourTable');
// set all activity columns
$uStatFields = UserHourTable::getEntity()->getFields();
foreach ($uStatFields as $uStatField) {
if ($uStatField instanceof Entity\ScalarField && !$uStatField->isPrimary()) {
$query->addSelect(new Entity\ExpressionField($uStatField->getName() . '_SUM', 'SUM(%s)', $uStatField->getName()));
}
}
// add & automatically group by hour
$query->addSelect('HOUR');
// add filter by date
if ($hour !== null) {
$query->setFilter(array('>=HOUR' => \ConvertTimeStamp($hour->getTimestamp(), 'FULL')));
}
// collect activity
$activity = array();
$result = $query->exec();
while ($row = $result->fetch()) {
foreach ($row as $k => $v) {
if (substr($k, -4) === '_SUM') {
$row[substr($k, 0, -4)] = $v;
unset($row[$k]);
}
}
$activity[] = $row;
}
return $activity;
}
示例13:
if ($arParams["ADD_SECTIONS_CHAIN"] && !empty($arResult["SECTION"]["PATH"]) && is_array($arResult["SECTION"]["PATH"]))
{
foreach($arResult["SECTION"]["PATH"] as $arPath)
{
if ($arPath["IPROPERTY_VALUES"]["SECTION_PAGE_TITLE"] != "")
$APPLICATION->AddChainItem($arPath["IPROPERTY_VALUES"]["SECTION_PAGE_TITLE"], $arPath["~SECTION_PAGE_URL"]);
else
$APPLICATION->AddChainItem($arPath["NAME"], $arPath["~SECTION_PAGE_URL"]);
}
}
if ($arParams["ADD_ELEMENT_CHAIN"])
{
if ($arResult["IPROPERTY_VALUES"]["ELEMENT_PAGE_TITLE"] != "")
$APPLICATION->AddChainItem($arResult["IPROPERTY_VALUES"]["ELEMENT_PAGE_TITLE"]);
else
$APPLICATION->AddChainItem($arResult["NAME"]);
}
if ($arParams["SET_LAST_MODIFIED"] && $arResult["TIMESTAMP_X"])
{
Context::getCurrent()->getResponse()->setLastModified(DateTime::createFromUserTime($arResult["TIMESTAMP_X"]));
}
return $arResult["ID"];
}
else
{
return 0;
}
?>
示例14: onBeforeSave
/**
* @param array $userfield
* @param Type\Date|string $value
*
* @return Type\Date
*/
public function onBeforeSave($userfield, $value)
{
if (strlen($value) && !$value instanceof Type\Date) {
// try both site's format - short and full
try {
$value = new Type\Date($value);
} catch (Main\ObjectException $e) {
$value = new Type\Date($value, Type\DateTime::getFormat());
}
}
return $value;
}
示例15: SearchDateChatMessage
function SearchDateChatMessage($searchDate, $chatId, $bTimeZone = true)
{
global $DB;
$chatId = IntVal($chatId);
$sqlHelper = Bitrix\Main\Application::getInstance()->getConnection()->getSqlHelper();
try {
$dateStart = \Bitrix\Main\Type\DateTime::createFromUserTime($searchDate);
$sqlDateStart = $sqlHelper->getCharToDateFunction($dateStart->format("Y-m-d H:i:s"));
$dateEnd = $dateStart->add('1 DAY');
$sqlDateEnd = $sqlHelper->getCharToDateFunction($dateEnd->format("Y-m-d H:i:s"));
} catch (\Bitrix\Main\ObjectException $e) {
$GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_HISTORY_SEARCH_DATE_EMPTY"), "ERROR_SEARCH_EMPTY");
return false;
}
$limitById = '';
$ar = \CIMChat::GetRelationById($chatId, $this->user_id);
if ($ar && $ar['START_ID'] > 0) {
$limitById = 'AND M.ID >= ' . intval($ar['START_ID']);
}
if (!$bTimeZone) {
CTimeZone::Disable();
}
$strSql = "\n\t\t\tSELECT\n\t\t\t\tM.ID,\n\t\t\t\tM.CHAT_ID,\n\t\t\t\tM.MESSAGE,\n\t\t\t\t" . $DB->DatetimeToTimestampFunction('M.DATE_CREATE') . " DATE_CREATE,\n\t\t\t\tM.AUTHOR_ID\n\t\t\tFROM b_im_relation R1\n\t\t\tINNER JOIN b_im_message M ON M.CHAT_ID = R1.CHAT_ID\n\t\t\tWHERE\n\t\t\t\tR1.USER_ID = " . $this->user_id . "\n\t\t\tAND R1.CHAT_ID = " . $chatId . "\n\t\t\tAND R1.MESSAGE_TYPE <> '" . IM_MESSAGE_PRIVATE . "'\n\t\t\tAND M.DATE_CREATE >= " . $sqlDateStart . " AND M.DATE_CREATE <= " . $sqlDateEnd . "\n\t\t\t\t" . $limitById . "\n\t\t\tORDER BY M.DATE_CREATE DESC, M.ID DESC\n\t\t";
if (!$bTimeZone) {
CTimeZone::Enable();
}
$dbRes = $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
$arMessages = array();
$arMessageId = array();
$arUnreadMessage = array();
$usersMessage = array();
$CCTP = new CTextParser();
$CCTP->MaxStringLen = 200;
$CCTP->allow = array("HTML" => "N", "ANCHOR" => $this->bHideLink ? "N" : "Y", "BIU" => "Y", "IMG" => "N", "QUOTE" => "N", "CODE" => "N", "FONT" => "N", "LIST" => "N", "SMILES" => $this->bHideLink ? "N" : "Y", "NL2BR" => "Y", "VIDEO" => "N", "TABLE" => "N", "CUT_ANCHOR" => "N", "ALIGN" => "N");
while ($arRes = $dbRes->Fetch()) {
$arMessages[$arRes['ID']] = array('id' => $arRes['ID'], 'chatId' => $arRes['CHAT_ID'], 'senderId' => $arRes['AUTHOR_ID'], 'recipientId' => $arRes['CHAT_ID'], 'date' => $arRes['DATE_CREATE'], 'text' => $CCTP->convertText(htmlspecialcharsbx($arRes['MESSAGE'])));
$usersMessage[$arRes['CHAT_ID']][] = $arRes['ID'];
$arMessageId[] = $arRes['ID'];
}
$params = CIMMessageParam::Get($arMessageId);
$arFiles = array();
foreach ($params as $messageId => $param) {
$arMessages[$messageId]['params'] = $param;
if (isset($param['FILE_ID'])) {
foreach ($param['FILE_ID'] as $fileId) {
$arFiles[$fileId] = $fileId;
}
}
}
$arMessageFiles = CIMDisk::GetFiles($chatId, $arFiles);
return array('chatId' => $chatId, 'message' => $arMessages, 'unreadMessage' => $arUnreadMessage, 'usersMessage' => $usersMessage, 'files' => $arMessageFiles);
}