本文整理汇总了PHP中Drupal\Core\Datetime\DrupalDateTime类的典型用法代码示例。如果您正苦于以下问题:PHP DrupalDateTime类的具体用法?PHP DrupalDateTime怎么用?PHP DrupalDateTime使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DrupalDateTime类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: valueCallback
/**
* {@inheritdoc}
*
* Validates the date type to adjust 12 hour time and prevent invalid dates.
* If the date is valid, the date is set in the form.
*/
public static function valueCallback(&$element, $input, FormStateInterface $form_state)
{
$parts = $element['#date_part_order'];
$increment = $element['#date_increment'];
$date = NULL;
if ($input !== FALSE) {
$return = $input;
if (isset($input['ampm'])) {
if ($input['ampm'] == 'pm' && $input['hour'] < 12) {
$input['hour'] += 12;
} elseif ($input['ampm'] == 'am' && $input['hour'] == 12) {
$input['hour'] -= 12;
}
unset($input['ampm']);
}
$timezone = !empty($element['#date_timezone']) ? $element['#date_timezone'] : NULL;
$date = DrupalDateTime::createFromArray($input, $timezone);
if ($date instanceof DrupalDateTime && !$date->hasErrors()) {
static::incrementRound($date, $increment);
}
} else {
$return = array_fill_keys($parts, '');
if (!empty($element['#default_value'])) {
$date = $element['#default_value'];
if ($date instanceof DrupalDateTime && !$date->hasErrors()) {
static::incrementRound($date, $increment);
foreach ($parts as $part) {
switch ($part) {
case 'day':
$format = 'j';
break;
case 'month':
$format = 'n';
break;
case 'year':
$format = 'Y';
break;
case 'hour':
$format = in_array('ampm', $element['#date_part_order']) ? 'g' : 'G';
break;
case 'minute':
$format = 'i';
break;
case 'second':
$format = 's';
break;
case 'ampm':
$format = 'a';
break;
default:
$format = '';
}
$return[$part] = $date->format($format);
}
}
}
}
$return['object'] = $date;
return $return;
}
示例2: hook_date_default_argument_alter
/**
* Alter the default value for a date argument.
*
* @param object $argument
* The argument object.
* @param string $value
* The default value created by the argument handler.
*/
function hook_date_default_argument_alter(&$argument, &$value)
{
$style_options = $style_options = $argument->view->display_handler->get_option('style_options');
if (!empty($style_options['track_date'])) {
$default_date = new DrupalDateTime();
$value = $default_date->format($argument->arg_format);
}
}
示例3: setDateTime
/**
* {@inheritdoc}
*/
public function setDateTime(DrupalDateTime $dateTime, $notify = TRUE)
{
$this->value = $dateTime->getTimestamp();
// Notify the parent of any changes.
if ($notify && isset($this->parent)) {
$this->parent->onChange($this->name);
}
}
示例4: settingsForm
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state)
{
$form = parent::settingsForm($form, $form_state);
$time = new DrupalDateTime();
$format_types = $this->dateFormatStorage->loadMultiple();
$options = [];
foreach ($format_types as $type => $type_info) {
$format = $this->dateFormatter->format($time->format('U'), $type);
$options[$type] = $type_info->label() . ' (' . $format . ')';
}
$form['format_type'] = array('#type' => 'select', '#title' => t('Date format'), '#description' => t("Choose a format for displaying the date. Be sure to set a format appropriate for the field, i.e. omitting time for a field that only has a date."), '#options' => $options, '#default_value' => $this->getSetting('format_type'));
return $form;
}
示例5: testDateTimezone
/**
* Test that DrupalDateTime can detect the right timezone to use.
* Test with a variety of less commonly used timezone names to
* help ensure that the system timezone will be different than the
* stated timezones.
*/
public function testDateTimezone()
{
global $user;
$date_string = '2007-01-31 21:00:00';
// Make sure no site timezone has been set.
\Drupal::config('system.date')->set('timezone.user.configurable', 0)->set('timezone.default', NULL)->save();
// Detect the system timezone.
$system_timezone = date_default_timezone_get();
// Create a date object with an unspecified timezone, which should
// end up using the system timezone.
$date = new DrupalDateTime($date_string);
$timezone = $date->getTimezone()->getName();
$this->assertTrue($timezone == $system_timezone, 'DrupalDateTime uses the system timezone when there is no site timezone.');
// Create a date object with a specified timezone.
$date = new DrupalDateTime($date_string, 'America/Yellowknife');
$timezone = $date->getTimezone()->getName();
$this->assertTrue($timezone == 'America/Yellowknife', 'DrupalDateTime uses the specified timezone if provided.');
// Set a site timezone.
\Drupal::config('system.date')->set('timezone.default', 'Europe/Warsaw')->save();
// Create a date object with an unspecified timezone, which should
// end up using the site timezone.
$date = new DrupalDateTime($date_string);
$timezone = $date->getTimezone()->getName();
$this->assertTrue($timezone == 'Europe/Warsaw', 'DrupalDateTime uses the site timezone if provided.');
// Create user.
\Drupal::config('system.date')->set('timezone.user.configurable', 1)->save();
$test_user = $this->drupalCreateUser(array());
$this->drupalLogin($test_user);
// Set up the user with a different timezone than the site.
$edit = array('mail' => $test_user->getEmail(), 'timezone' => 'Asia/Manila');
$this->drupalPostForm('user/' . $test_user->id() . '/edit', $edit, t('Save'));
// Disable session saving as we are about to modify the global $user.
\Drupal::service('session_manager')->disable();
// Save the original user and then replace it with the test user.
$real_user = $user;
$user = user_load($test_user->id(), TRUE);
// Simulate a Drupal bootstrap with the logged-in user.
date_default_timezone_set(drupal_get_user_timezone());
// Create a date object with an unspecified timezone, which should
// end up using the user timezone.
$date = new DrupalDateTime($date_string);
$timezone = $date->getTimezone()->getName();
$this->assertTrue($timezone == 'Asia/Manila', 'DrupalDateTime uses the user timezone, if configurable timezones are used and it is set.');
// Restore the original user, and enable session saving.
$user = $real_user;
// Restore default time zone.
date_default_timezone_set(drupal_get_user_timezone());
\Drupal::service('session_manager')->enable();
}
示例6: testTaxonomyLegacyNode
/**
* Test taxonomy functionality with nodes prior to 1970.
*/
function testTaxonomyLegacyNode()
{
// Posts an article with a taxonomy term and a date prior to 1970.
$date = new DrupalDateTime('1969-01-01 00:00:00');
$edit = array();
$edit['title[0][value]'] = $this->randomMachineName();
$edit['created[0][value][date]'] = $date->format('Y-m-d');
$edit['created[0][value][time]'] = $date->format('H:i:s');
$edit['body[0][value]'] = $this->randomMachineName();
$edit['field_tags[target_id]'] = $this->randomMachineName();
$this->drupalPostForm('node/add/article', $edit, t('Save and publish'));
// Checks that the node has been saved.
$node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
$this->assertEqual($node->getCreatedTime(), $date->getTimestamp(), 'Legacy node was saved with the right date.');
}
示例7: buildForm
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state)
{
$default_role_choices = user_role_names(TRUE);
unset($default_role_choices[DRUPAL_AUTHENTICATED_RID]);
$roles_config = $this->config('uc_role.settings');
if (!count($default_role_choices)) {
$form['no_roles'] = array('#markup' => $this->t('You need to <a href=":url">create new roles</a> before any can be added as product features.', [':url' => Url::fromRoute('user.role_add', [], ['query' => ['destination' => 'admin/store/config/products']])->toString()]), '#prefix' => '<p>', '#suffix' => '</p>');
return $form;
}
$form['default_role'] = array('#type' => 'select', '#title' => $this->t('Default role'), '#default_value' => $roles_config->get('default_role'), '#description' => $this->t('The default role Ubercart grants on specified products.'), '#options' => _uc_role_get_choices());
$form['default_role_choices'] = array('#type' => 'checkboxes', '#title' => $this->t('Product roles'), '#default_value' => $roles_config->get('default_role_choices'), '#multiple' => TRUE, '#description' => $this->t('These are roles that Ubercart can grant to customers who purchase specified products. If you leave all roles unchecked, they will all be eligible for adding to a product.'), '#options' => $default_role_choices);
$form['role_lifetime'] = array('#type' => 'fieldset', '#title' => $this->t('Default role expiration'));
$form['role_lifetime']['default_end_expiration'] = array('#type' => 'select', '#title' => $this->t('Expiration type'), '#options' => array('rel' => $this->t('Relative to purchase date'), 'abs' => $this->t('Fixed date')), '#default_value' => $roles_config->get('default_end_expiration'));
$form['role_lifetime']['default_length'] = array('#type' => 'textfield', '#default_value' => $roles_config->get('default_granularity') == 'never' ? NULL : $roles_config->get('default_length'), '#size' => 4, '#maxlength' => 4, '#prefix' => '<div class="expiration">', '#suffix' => '</div>', '#states' => array('visible' => array('select[name="default_end_expiration"]' => array('value' => 'rel')), 'invisible' => array('select[name="default_granularity"]' => array('value' => 'never'))));
$form['role_lifetime']['default_granularity'] = array('#type' => 'select', '#default_value' => $roles_config->get('default_granularity'), '#options' => array('never' => $this->t('never'), 'day' => $this->t('day(s)'), 'week' => $this->t('week(s)'), 'month' => $this->t('month(s)'), 'year' => $this->t('year(s)')), '#description' => $this->t('From the time the role was purchased.'), '#prefix' => '<div class="expiration">', '#suffix' => '</div>', '#states' => array('visible' => array('select[name="default_end_expiration"]' => array('value' => 'rel'))));
$form['role_lifetime']['absolute'] = array('#type' => 'container', '#states' => array('visible' => array('select[name="default_end_expiration"]' => array('value' => 'abs'))));
$date = (int) $roles_config->get('default_end_time');
$date = !empty($date) ? DrupalDateTime::createFromTimestamp($date) : DrupalDateTime::createFromTimestamp(REQUEST_TIME);
$form['role_lifetime']['absolute']['default_end_time'] = array('#type' => 'datetime', '#description' => $this->t('Expire the role at the beginning of this day.'), '#date_date_element' => 'date', '#date_time_element' => 'none', '#default_value' => $date);
$form['role_lifetime']['default_by_quantity'] = array('#type' => 'checkbox', '#title' => $this->t('Multiply by quantity'), '#description' => $this->t('Check if the role duration should be multiplied by the quantity purchased.'), '#default_value' => $roles_config->get('default_by_quantity'));
$form['reminder']['reminder_length'] = array('#type' => 'textfield', '#title' => $this->t('Time before reminder'), '#default_value' => $roles_config->get('reminder_granularity') == 'never' ? NULL : $roles_config->get('reminder_length'), '#size' => 4, '#maxlength' => 4, '#prefix' => '<div class="expiration">', '#suffix' => '</div>', '#states' => array('disabled' => array('select[name="reminder_granularity"]' => array('value' => 'never'))));
$form['reminder']['reminder_granularity'] = array('#type' => 'select', '#default_value' => $roles_config->get('reminder_granularity'), '#options' => array('never' => $this->t('never'), 'day' => $this->t('day(s)'), 'week' => $this->t('week(s)'), 'month' => $this->t('month(s)'), 'year' => $this->t('year(s)')), '#description' => $this->t('The amount of time before a role expiration takes place that a customer is notified of its expiration.'), '#prefix' => '<div class="expiration">', '#suffix' => '</div>');
$form['default_show_expiration'] = array('#type' => 'checkbox', '#title' => $this->t('Show expirations on user page'), '#default_value' => $roles_config->get('default_show_expiration'), '#description' => $this->t('If users have any role expirations they will be displayed on their account page.'));
return parent::buildForm($form, $form_state);
}
示例8: massageFormValues
/**
* {@inheritdoc}
*/
public function massageFormValues(array $values, array $form, FormStateInterface $form_state)
{
foreach ($values as &$item) {
// @todo The structure is different whether access is denied or not, to
// be fixed in https://www.drupal.org/node/2326533.
if (isset($item['value']) && $item['value'] instanceof DrupalDateTime) {
$date = $item['value'];
} elseif (isset($item['value']['object']) && $item['value']['object'] instanceof DrupalDateTime) {
$date = $item['value']['object'];
} else {
$date = new DrupalDateTime();
}
$item['value'] = $date->getTimestamp();
}
return $values;
}
示例9: valueCallback
/**
* {@inheritdoc}
*/
public static function valueCallback(&$element, $input, FormStateInterface $form_state)
{
if ($input !== FALSE) {
$date_input = $element['#date_date_element'] != 'none' && !empty($input['date']) ? $input['date'] : '';
$time_input = $element['#date_time_element'] != 'none' && !empty($input['time']) ? $input['time'] : '';
$date_format = $element['#date_date_element'] != 'none' ? static::getHtml5DateFormat($element) : '';
$time_format = $element['#date_time_element'] != 'none' ? static::getHtml5TimeFormat($element) : '';
$timezone = !empty($element['#date_timezone']) ? $element['#date_timezone'] : NULL;
// Seconds will be omitted in a post in case there's no entry.
if (!empty($time_input) && strlen($time_input) == 5) {
$time_input .= ':00';
}
try {
$date_time_format = trim($date_format . ' ' . $time_format);
$date_time_input = trim($date_input . ' ' . $time_input);
$date = DrupalDateTime::createFromFormat($date_time_format, $date_time_input, $timezone);
} catch (\Exception $e) {
$date = NULL;
}
$input = array('date' => $date_input, 'time' => $time_input, 'object' => $date);
} else {
$date = $element['#default_value'];
if ($date instanceof DrupalDateTime && !$date->hasErrors()) {
$input = array('date' => $date->format($element['#date_date_format']), 'time' => $date->format($element['#date_time_format']), 'object' => $date);
} else {
$input = array('date' => '', 'time' => '', 'object' => NULL);
}
}
return $input;
}
示例10: buildForm
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, OrderInterface $uc_order = NULL)
{
$balance = uc_payment_balance($uc_order);
$form['balance'] = array('#prefix' => '<strong>' . $this->t('Order balance:') . '</strong> ', '#markup' => uc_currency_format($balance));
$form['order_id'] = array('#type' => 'hidden', '#value' => $uc_order->id());
$form['amount'] = array('#type' => 'uc_price', '#title' => $this->t('Check amount'), '#default_value' => $balance);
$form['comment'] = array('#type' => 'textfield', '#title' => $this->t('Comment'), '#description' => $this->t('Any notes about the check, like type or check number.'), '#size' => 64, '#maxlength' => 256);
$form['clear_date'] = array('#type' => 'datetime', '#title' => $this->t('Expected clear date'), '#date_date_element' => 'date', '#date_time_element' => 'none', '#default_value' => DrupalDateTime::createFromTimestamp(REQUEST_TIME));
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Receive check'));
return $form;
}
示例11: testDateTimezone
/**
* Test that DrupalDateTime can detect the right timezone to use.
* Test with a variety of less commonly used timezone names to
* help ensure that the system timezone will be different than the
* stated timezones.
*/
public function testDateTimezone()
{
$date_string = '2007-01-31 21:00:00';
// Make sure no site timezone has been set.
$this->config('system.date')->set('timezone.user.configurable', 0)->set('timezone.default', NULL)->save();
// Detect the system timezone.
$system_timezone = date_default_timezone_get();
// Create a date object with an unspecified timezone, which should
// end up using the system timezone.
$date = new DrupalDateTime($date_string);
$timezone = $date->getTimezone()->getName();
$this->assertTrue($timezone == $system_timezone, 'DrupalDateTime uses the system timezone when there is no site timezone.');
// Create a date object with a specified timezone.
$date = new DrupalDateTime($date_string, 'America/Yellowknife');
$timezone = $date->getTimezone()->getName();
$this->assertTrue($timezone == 'America/Yellowknife', 'DrupalDateTime uses the specified timezone if provided.');
// Set a site timezone.
$this->config('system.date')->set('timezone.default', 'Europe/Warsaw')->save();
// Create a date object with an unspecified timezone, which should
// end up using the site timezone.
$date = new DrupalDateTime($date_string);
$timezone = $date->getTimezone()->getName();
$this->assertTrue($timezone == 'Europe/Warsaw', 'DrupalDateTime uses the site timezone if provided.');
// Create user.
$this->config('system.date')->set('timezone.user.configurable', 1)->save();
$test_user = $this->drupalCreateUser(array());
$this->drupalLogin($test_user);
// Set up the user with a different timezone than the site.
$edit = array('mail' => $test_user->getEmail(), 'timezone' => 'Asia/Manila');
$this->drupalPostForm('user/' . $test_user->id() . '/edit', $edit, t('Save'));
// Reload the user and reset the timezone in AccountProxy::setAccount().
\Drupal::entityManager()->getStorage('user')->resetCache();
$this->container->get('current_user')->setAccount(User::load($test_user->id()));
// Create a date object with an unspecified timezone, which should
// end up using the user timezone.
$date = new DrupalDateTime($date_string);
$timezone = $date->getTimezone()->getName();
$this->assertTrue($timezone == 'Asia/Manila', 'DrupalDateTime uses the user timezone, if configurable timezones are used and it is set.');
}
示例12: datetimeRangeYears
/**
* Specifies the start and end year to use as a date range.
*
* Handles a string like -3:+3 or 2001:2010 to describe a dynamic range of
* minimum and maximum years to use in a date selector.
*
* Centers the range around the current year, if any, but expands it far enough
* so it will pick up the year value in the field in case the value in the field
* is outside the initial range.
*
* @param string $string
* A min and max year string like '-3:+1' or '2000:2010' or '2000:+3'.
* @param object $date
* (optional) A date object to test as a default value. Defaults to NULL.
*
* @return array
* A numerically indexed array, containing the minimum and maximum year
* described by this pattern.
*/
protected static function datetimeRangeYears($string, $date = NULL)
{
$datetime = new DrupalDateTime();
$this_year = $datetime->format('Y');
list($min_year, $max_year) = explode(':', $string);
// Valid patterns would be -5:+5, 0:+1, 2008:2010.
$plus_pattern = '@[\\+|\\-][0-9]{1,4}@';
$year_pattern = '@^[0-9]{4}@';
if (!preg_match($year_pattern, $min_year, $matches)) {
if (preg_match($plus_pattern, $min_year, $matches)) {
$min_year = $this_year + $matches[0];
} else {
$min_year = $this_year;
}
}
if (!preg_match($year_pattern, $max_year, $matches)) {
if (preg_match($plus_pattern, $max_year, $matches)) {
$max_year = $this_year + $matches[0];
} else {
$max_year = $this_year;
}
}
// We expect the $min year to be less than the $max year. Some custom values
// for -99:+99 might not obey that.
if ($min_year > $max_year) {
$temp = $max_year;
$max_year = $min_year;
$min_year = $temp;
}
// If there is a current value, stretch the range to include it.
$value_year = $date instanceof DrupalDateTime ? $date->format('Y') : '';
if (!empty($value_year)) {
$min_year = min($value_year, $min_year);
$max_year = max($value_year, $max_year);
}
return array($min_year, $max_year);
}
示例13: prepareValue
/**
* {@inheritdoc}
*/
protected function prepareValue($delta, array &$values)
{
$date = FALSE;
$value = trim($values['value']);
if (is_numeric($value) || is_string($value) && ($value = strtotime($value))) {
$date = DrupalDateTime::createFromTimestamp($value, DATETIME_STORAGE_TIMEZONE);
} elseif ($value instanceof \DateTime) {
$date = DrupalDateTime::createFromDateTime($value);
}
if ($date && !$date->hasErrors()) {
$values['value'] = $date->format($this->storageFormat);
} else {
$values['value'] = '';
}
}
示例14: prepareValue
/**
* {@inheritdoc}
*/
protected function prepareValue($delta, array &$values)
{
$value = trim($values['value']);
// This is a year value.
if (ctype_digit($value) && strlen($value) === 4) {
$value = 'January ' . $value;
}
if (is_numeric($value) || ($value = strtotime($value))) {
$date = DrupalDateTime::createFromTimestamp($value, DATETIME_STORAGE_TIMEZONE);
}
if (isset($date) && !$date->hasErrors()) {
$values['value'] = $date->format($this->storageFormat);
} else {
$values['value'] = '';
}
}
示例15: getValue
/**
* {@inheritdoc}
*/
public function getValue($langcode = NULL)
{
if ($this->date !== NULL) {
return $this->date;
}
$item = $this->getParent();
$value = $item->{$this->definition->getSetting('date source')};
$storage_format = $item->getFieldDefinition()->getSetting('datetime_type') == 'date' ? DATETIME_DATE_STORAGE_FORMAT : DATETIME_DATETIME_STORAGE_FORMAT;
try {
$date = DrupalDateTime::createFromFormat($storage_format, $value, DATETIME_STORAGE_TIMEZONE);
if ($date instanceof DrupalDateTime && !$date->hasErrors()) {
$this->date = $date;
}
} catch (\Exception $e) {
// @todo Handle this.
}
return $this->date;
}