diff --git a/core/includes/common.inc b/core/includes/common.inc
index 540f42b..09f9ce4 100644
--- a/core/includes/common.inc
+++ b/core/includes/common.inc
@@ -7,6 +7,7 @@
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Database\Database;
use Drupal\Core\Template\Attribute;
+use Drupal\Core\Datetime\DrupalDateTime;
/**
* @file
@@ -1997,26 +1998,12 @@ function format_date($timestamp, $type = 'medium', $format = '', $timezone = NUL
break;
}
- // Create a DateTime object from the timestamp.
- $date_time = date_create('@' . $timestamp);
- // Set the time zone for the DateTime object.
- date_timezone_set($date_time, $timezones[$timezone]);
-
- // Encode markers that should be translated. 'A' becomes '\xEF\AA\xFF'.
- // xEF and xFF are invalid UTF-8 sequences, and we assume they are not in the
- // input string.
- // Paired backslashes are isolated to prevent errors in read-ahead evaluation.
- // The read-ahead expression ensures that A matches, but not \A.
- $format = preg_replace(array('/\\\\\\\\/', '/(? $langcode);
+ return $date_time->format($format, $settings);
}
/**
@@ -2037,6 +2024,65 @@ function date_iso8601($date) {
}
/**
+ * Handle a string like -3:+3 or 2001:2010 to describe a dynamic range
+ * of minimum and maximum years to use in a date selector.
+ *
+ * Center the range around the current year, if any, but expand 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.
+ */
+function date_range_years($string, $date = NULL) {
+
+ // We use the full path to the date class to avoid the need to
+ // include this file when not being used.
+ $this_year = date_format(new \Drupal\Core\Datetime\DrupalDateTime(), '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 \Drupal\Core\Datetime\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);
+}
+
+/**
* Translates a formatted date string.
*
* Callback for preg_replace_callback() within format_date().
@@ -4996,7 +5042,8 @@ function drupal_page_set_cache($body) {
$cache->data['headers'][$header_names[$name_lower]] = $value;
if ($name_lower == 'expires') {
// Use the actual timestamp from an Expires header if available.
- $cache->expire = strtotime($value);
+ $date = new DrupalDateTime($value);
+ $cache->expire = $date->getTimestamp();
}
}
diff --git a/core/includes/form.inc b/core/includes/form.inc
index 6956f04..15cde7e 100644
--- a/core/includes/form.inc
+++ b/core/includes/form.inc
@@ -7,6 +7,7 @@
use Drupal\Core\Utility\Color;
use Drupal\Core\Template\Attribute;
+use Drupal\Core\Datetime\DrupalDateTime;
/**
* @defgroup forms Form builder functions
@@ -2922,18 +2923,49 @@ function password_confirm_validate($element, &$element_state) {
}
/**
- * Returns HTML for a date selection form element.
+ * Returns HTML for an #date form element.
*
- * @param $variables
+ * Supports HTML5 types of 'date', 'datetime', 'datetime-local', and
+ * 'time'. Falls back to a plain textfield. Used as a sub-element by the
+ * datetime element type.
+ *
+ * @param array $variables
* An associative array containing:
* - element: An associative array containing the properties of the element.
* Properties used: #title, #value, #options, #description, #required,
- * #attributes.
+ * #attributes, #id, #name, #type, #min, #max, #step, #value, #size.
*
* @ingroup themeable
*/
function theme_date($variables) {
$element = $variables['element'];
+ if (empty($element['attribute']['type'])) {
+ $element['attribute']['type'] = 'date';
+ }
+ element_set_attributes($element, array('id', 'name', 'type', 'min', 'max', 'step', 'value', 'size'));
+ _form_set_attributes($element, array('form-' . $element['attribute']['type']));
+
+ return '';
+}
+
+/**
+ * Returns HTML for a HTML5-compatible #datatime form element.
+ *
+ * Wrapper around the date element type which creates a date and a
+ * time component for a date.
+ *
+ * @param array $variables
+ * An associative array containing:
+ * - element: An associative array containing the properties of the element.
+ * Properties used: #title, #value, #options, #description, #required,
+ * #attributes.
+ *
+ * @ingroup themeable
+ * @see form_process_datetime()
+ */
+function theme_form_datetime($variables) {
+
+ $element = $variables['element'];
$attributes = array();
if (isset($element['#id'])) {
@@ -2948,91 +2980,452 @@ function theme_date($variables) {
}
/**
- * Expands a date element into year, month, and day select elements.
+ * Expands a #datetime element type into date and/or time elements.
+ *
+ * All form elements are designed to have sane defaults so any or all
+ * can be omitted. Both the date and time components are configurable
+ * so they can be output as HTML5 datetime elements or not, as
+ * desired.
+ *
+ * Examples of possible configurations include:
+ * HTML5 date and time:
+ * #date_date_element = 'date';
+ * #date_time_element = 'time';
+ * HTML5 datetime:
+ * #date_date_element = 'datetime';
+ * #date_time_element = 'none';
+ * HTML5 time only:
+ * #date_date_element = 'none';
+ * #date_time_element = 'time'
+ * Non-HTML5:
+ * #date_date_element = 'text';
+ * #date_time_element = 'text';
+ *
+ * Required settings:
+ * - #default_value: A DrupalDateTime object, adjusted to the proper
+ * local timezone. Converting a date stored in the database from UTC
+ * to the local zone and converting it back to UTC before storing it is
+ * not handled here. This element simply formats the date as a string
+ * in a date/time element as the default value, and then converts the
+ * user input strings back into a new date object on submission. No
+ * timezone adjustment is performed.
+ * Optional properties include:
+ * - #date_date_format: A date format string that describes the format that
+ * should be displayed to the end user for the date. When using HTML5
+ * elements the format MUST use the appropriate HTML5 format for that
+ * element, no other format will work. See the format_date() function for
+ * a list of the possible formats. Defaults to the right HTML5 format for
+ * the chosen element if a HTML5 element is used, or
+ * variable_get('date_format_html_date', 'Y-m-d').
+ * - #date_date_element: The date element.
+ * Options are:
+ * - datetime: Use the HTML5 datetime element type
+ * - datetime-local: Use the HTML5 datetime-local element type
+ * - date: Use the HTML5 date element type
+ * - text: No HTML5 element, use a normal text field
+ * - none: Do not display a date element
+ * - #date_date_callbacks: Array of optional callbacks for the date element.
+ * Can be used to add a jQuery datepicker, for instance. Drupal provides the
+ * 'datetime_jquery_datepicker_callback' as one possible choice.
+ * - #date_time_element: The time element.
+ * Options are:
+ * - time: Use a HTML5 time element type
+ * - text: No HTML5 element, use a normal text field
+ * - none: Do not display a time element
+ * - #date_time_format: A date format string that describes the format that
+ * should be displayed to the end user for the time. When using HTML5
+ * elements the format MUST use the appropriate HTML5 format for that
+ * element, no other format will work. See the format_date() function for
+ * a list of the possible formats and HTML5 standards for the HTML5
+ * requirements. Defaults to the right HTML5 format for the chosen
+ * element if a HTML5 element is used, otherwise defaults to
+ * variable_get('date_format_html_time', 'H:i:s').
+ * - #date_time_callbacks: An array of optional callbacks for the time
+ * element. Can be used to add a jQuery timepicker or an 'All day' checkbox.
+ * - #date_year_range: A description of the range of years to allow, like
+ * '1900:2050', '-3:+3' or '2000:+3', where the first value describes the
+ * earliest year and the second the latest year in the range. A year
+ * in either position means that specific year. A +/- value describes a
+ * dynamic value that is that many years earlier or later than the current
+ * year at the time the form is displayed. Used in jQueryUI datepicker year
+ * range and HTML5 min/max date settings. Defaults to '1900:2050'.
+ * - #date_increment: The increment to use for minutes and seconds, i.e.
+ * '15' would show only :00, :15, :30 and :45. Used for HTML5 step values and
+ * jQueryUI datepicker settings. Defaults to 1 to show every minute.
+ * - #date_timezone: The local timezone to use when creating dates. Generally
+ * this should be left empty and it will be set correctly for the user using
+ * the form. Useful if the default value is empty to designate a desired
+ * timezone for dates created in form processing. If a default date is
+ * provided, this value will be ignored, the timezone in the default date
+ * takes precedence. Defaults to the value returned by
+ * drupal_get_user_timezone().
+ *
+ * Example usage:
+ * @code
+ * $form = array(
+ * '#type' => 'datetime',
+ * '#default_value' => '2000-01-01 00:00:00',
+ * '#date_date_callbacks' => array('datetime_jquery_datepicker_callback'),
+ * '#date_date_element' => 'date',
+ * '#date_time_element' => 'none',
+ * '#date_year_range' => '2010:+3',
+ * );
+ * @endcode
*/
-function form_process_date($element) {
- // Default to current date
- if (empty($element['#value'])) {
- $element['#value'] = array(
- 'day' => format_date(REQUEST_TIME, 'custom', 'j'),
- 'month' => format_date(REQUEST_TIME, 'custom', 'n'),
- 'year' => format_date(REQUEST_TIME, 'custom', 'Y'),
- );
+function form_process_datetime($element, &$form_state) {
+
+ // The value callback has populated the #value array.
+ $date = !empty($element['#value']['object']) ? $element['#value']['object'] : NULL;
+
+ // Set a fallback timezone.
+ if ($date instanceOf DrupalDateTime) {
+ $element['#date_timezone'] = $date->getTimezone()->getName();
+ }
+ elseif (!empty($element['#timezone'])) {
+ $element['#date_timezone'] = $element['#date_timezone'];
+ }
+ else {
+ $element['#date_timezone'] = drupal_get_user_timezone();
}
$element['#tree'] = TRUE;
- // Determine the order of day, month, year in the site's chosen date format.
- $format = variable_get('date_format_short', 'm/d/Y - H:i');
- $sort = array();
- $sort['day'] = max(strpos($format, 'd'), strpos($format, 'j'));
- $sort['month'] = max(strpos($format, 'm'), strpos($format, 'M'));
- $sort['year'] = strpos($format, 'Y');
- asort($sort);
- $order = array_keys($sort);
-
- // Output multi-selector for date.
- foreach ($order as $type) {
- switch ($type) {
- case 'day':
- $options = drupal_map_assoc(range(1, 31));
- $title = t('Day');
- break;
-
- case 'month':
- $options = drupal_map_assoc(range(1, 12), 'map_month');
- $title = t('Month');
- break;
-
- case 'year':
- $options = drupal_map_assoc(range(1900, 2050));
- $title = t('Year');
- break;
- }
-
- $element[$type] = array(
- '#type' => 'select',
- '#title' => $title,
+ if ($element['#date_date_element'] != 'none') {
+
+ $date_format = $element['#date_date_element'] != 'none' ? datetime_html5_format('date', $element) : '';
+ $date_value = !empty($date) ? $date->format($date_format) : $element['#value']['date'];
+
+ // Creating format examples on every individual date item is messy,
+ // and placeholders are invalid for HTML5 date and datetime, so an
+ // example format is appended to the title to appear in tooltips.
+ $extra_attributes = array(
+ 'title' => t('Date (i.e. %format)', array('%format' => datetime_format_example($date_format))),
+ 'type' => $element['#date_date_element'],
+ );
+
+ // Adds the HTML5 date attributes.
+ if ($date instanceOf DrupalDateTime && !$date->hasErrors()) {
+ $html5_min = clone($date);
+ $range = date_range_years($element['#date_year_range'], $date);
+ $html5_min->setDate($range[0], 1, 1)->setTime(0, 0, 0);
+ $html5_max = clone($date);
+ $html5_max->setDate($range[1], 12, 31)->setTime(23, 59, 59);
+
+ $extra_attributes += array(
+ 'min' => $html5_min->format($date_format),
+ 'max' => $html5_max->format($date_format),
+ );
+ }
+
+ $element['date'] = array(
+ '#type' => 'date',
+ '#title' => t('Date'),
+ '#title_display' => 'invisible',
+ '#value' => $date_value,
+ '#attributes' => $element['#attributes'] + $extra_attributes,
+ '#required' => $element['#required'],
+ '#size' => max(12, strlen($element['#value']['date'])),
+ );
+
+ // Allows custom callbacks to alter the element.
+ if (!empty($element['#date_date_callbacks'])) {
+ foreach ($element['#date_date_callbacks'] as $callback) {
+ if (function_exists($callback)) {
+ $callback($element, $form_state, $date);
+ }
+ }
+ }
+ }
+
+ if ($element['#date_time_element'] != 'none') {
+
+ $time_format = $element['#date_time_element'] != 'none' ? datetime_html5_format('time', $element) : '';
+ $time_value = !empty($date) ? $date->format($time_format) : $element['#value']['time'];
+
+ // Adds the HTML5 attributes.
+ $extra_attributes = array(
+ 'title' =>t('Time (i.e. %format)', array('%format' => datetime_format_example($time_format))),
+ 'type' => $element['#date_time_element'],
+ 'step' => ($element['#date_increment'] * 60),
+ );
+ $element['time'] = array(
+ '#type' => 'date',
+ '#title' => t('Time'),
'#title_display' => 'invisible',
- '#value' => $element['#value'][$type],
- '#attributes' => $element['#attributes'],
- '#options' => $options,
+ '#value' => $time_value,
+ '#attributes' => $element['#attributes'] + $extra_attributes,
+ '#required' => $element['#required'],
+ '#size' => 12,
);
+
+ // Allows custom callbacks to alter the element.
+ if (!empty($element['#date_time_callbacks'])) {
+ foreach ($element['#date_time_callbacks'] as $callback) {
+ if (function_exists($callback)) {
+ $callback($element, $form_state, $date);
+ }
+ }
+ }
}
return $element;
}
/**
- * Validates the date type to prevent invalid dates (e.g., February 30, 2006).
+ * Value callback for a datetime element.
+ *
+ * @param array $element
+ * The form element whose value is being populated.
+ * @param array $input
+ * The incoming input to populate the form element. If this is FALSE,
+ * the element's default value should be returned.
+ *
+ * @return array
+ * The data that will appear in the $element_state['values'] collection
+ * for this element. Return nothing to use the default.
+ */
+function form_type_datetime_value($element, $input = FALSE) {
+
+ 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' ? datetime_html5_format('date', $element['#date_date_format']) : '';
+ $time_format = $element['#date_time_element'] != 'none' ? datetime_html5_format('time', $element['#date_time_format']) : '';
+ $timezone = !empty($element['#date_timezone']) ? $element['#date_timezone'] : NULL;
+ $date = new DrupalDateTime(trim($date_input . ' ' . $time_input), $timezone, trim($date_format . ' ' . $time_format));
+ $input = array(
+ 'date' => $date_input,
+ 'time' => $time_input,
+ 'object' => $date instanceOf DrupalDateTime && !$date->hasErrors() ? $date : NULL,
+ );
+ }
+ 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;
+}
+
+/**
+ * Validates the date and sets errors.
+ *
+ * If the date is valid, the date is set in the element as a string
+ * using __toString().
+ */
+function datetime_validate($element, &$form_state) {
+
+ $input_exists = FALSE;
+ $input = drupal_array_get_nested_value($form_state['values'], $element['#parents'], $input_exists);
+ if ($input_exists) {
+
+ $title = !empty($element['#title']) ? $element['#title'] : '';
+ $date_format = $element['#date_date_element'] != 'none' ? datetime_html5_format('date', $element) : '';
+ $time_format = $element['#date_time_element'] != 'none' ? datetime_html5_format('time', $element) : '';
+ $format = trim($date_format . ' ' . $time_format);
+
+ // If there's empty input and the field is not required, set it to empty.
+ if (empty($input['date']) && empty($input['time']) && !$element['#required']) {
+ form_set_value($element, NULL, $form_state);
+ }
+ // If there's empty input and the field is required, set an error.
+ // A reminder of the required format in the message is a better UX.
+ elseif (empty($input['date']) && empty($input['time']) && $element['#required']) {
+ form_error($element, t('The %field date is required. Please enter a date in the format %format.', array('%field' => $title, '%format' => datetime_format_example($format))));
+ }
+ else {
+ // If there's a date with no errors, set the value.
+ $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 = new DrupalDateTime(trim($date_input . ' ' . $time_input), $element['#date_timezone'], $format);
+ if ($date instanceOf DrupalDateTime && !$date->hasErrors()) {
+ form_set_value($element, $date, $form_state);
+ }
+ // If the input is invalid, set an error. A reminder of the required
+ // format in the message is a better UX.
+ else {
+ form_error($element, t('The %field date is invalid. Please enter a date in the format %format.', array('%field' => $title, '%format' => datetime_format_example($format))));
+ }
+ }
+ }
+}
+
+/**
+ * Callback to add the jQuery datepicker to a date element.
+ *
+ * The javascript in drupal.datepicker will check first for HTML5
+ * compliance, and then apply the jQuery datepicker as a fallback,
+ * only if the HTML5 widget is not supported.
+ *
+ * @param array $element
+ * The 'date' element being altered.
+ * @param array $form_state
+ * The form state array.
+ * @param object $date
+ * The date object being manipulated by this element.
+ */
+function datetime_jquery_datepicker_callback(&$element, &$form_state, $date) {
+
+ // Get the format used by the element, and then convert it to
+ // the format needed by the datepicker.
+ $element_format = datetime_html5_format('date', $element);
+ $datepicker_format = datetime_datepicker_format($element_format);
+
+ // Make sure the date range includes the current year to avoid odd
+ // behavior when the datepicker doesn't find it in the date range.
+ // The date_range_years function will ensure the current date is
+ // included in the range.
+ $range = date_range_years($element['#date_year_range'], $date);
+
+ $settings = array(
+ 'changeMonth' => 'true',
+ 'changeYear' => 'true',
+ 'autoPopUp' => 'focus',
+ 'closeAtTop' => 'false',
+ 'speed' => 'immediate',
+ 'firstDay' => intval(variable_get('date_first_day', 0)),
+ 'dateFormat' => $datepicker_format,
+ 'yearRange' => $range[0] . ':' . $range[1],
+ );
+
+ // There could be an unknown number of instances of the datepicker
+ // on any page. Set a unique id for each element and its settings.
+ $new_id = datepicker_settings_id($element['#id'], $settings, $date);
+ $element['date']['#id'] = $new_id;
+
+ $js_settings = array(
+ 'type' => 'setting',
+ 'data' => array(
+ 'dateTime' => array(
+ '#' . $new_id => $settings,
+ ),
+ ),
+ );
+ $element['#attached']['js'][] = $js_settings;
+ $element['#attached']['library'][] = array('system', 'jquery.ui.datepicker');
+ $element['#attached']['library'][] = array('system', 'drupal.datepicker');
+}
+
+/**
+ * Creates a unique id for a datepicker element.
+ *
+ * A central function and static for creating a unique id for as
+ * many datepicker elements as might be created, to be used by multiple
+ * datepicker elements across a page request.
+ *
+ * @param string $id
+ * The id of the element that contains the datepicker.
+ * @param array $settings
+ * The settings array to pass to the jQuery function.
+ *
+ * @returns string
+ * The CSS id to assign to the element that should have
+ * $func($settings) invoked on it.
+ */
+function datepicker_settings_id($id, &$settings, $date) {
+ static $id_count = array();
+
+ // Uses a static array to account for possible multiple form_builder()
+ // calls in the same request (for instance on 'Preview') and when
+ // there are multiple values, as with multiple value fields.
+ if (!isset($id_count[$id])) {
+ $id_count[$id] = 0;
+ }
+ return "$id-datepicker-" . $id_count[$id]++;
+}
+
+/**
+ * Alters the format string to comply with jQuery datepicker requirements.
+ *
+ * Used to transform a date format that uses the PHP format
+ * strings to the format used by the datepicker.
+ *
+ * @param string $format
+ * A standard PHP format string.
+ *
+ * @return string
+ * Returns the format string formatted correctly for the jQuery
+ * timepicker.
+ */
+function datetime_datepicker_format($format) {
+ $replace = array(
+ 'd' => 'dd',
+ 'j' => 'd',
+ 'l' => 'DD',
+ 'D' => 'D',
+ 'm' => 'mm',
+ 'n' => 'm',
+ 'F' => 'MM',
+ 'M' => 'M',
+ 'Y' => 'yy',
+ 'y' => 'y',
+ );
+ return strtr($format, $replace);
+}
+
+/**
+ * Retrieves the right format for a HTML5 date element.
+ *
+ * The format is mportant because these elements will not
+ * work with any other format.
+ *
+ * @param string $part
+ * The type of element format to retrieve.
+ * @param string $element
+ * The $element to assess.
+ *
+ * @return string
+ * Returns the right format for the type of element, or
+ * the original format if this is not a HTML5 element.
*/
-function date_validate($element) {
- if (!checkdate($element['#value']['month'], $element['#value']['day'], $element['#value']['year'])) {
- form_error($element, t('The specified date is invalid.'));
+function datetime_html5_format($part, $element) {
+ switch ($part) {
+ case 'date':
+ switch ($element['#date_date_element']) {
+ case 'date':
+ return variable_get('date_format_html_date', 'Y-m-d');
+ case 'datetime':
+ case 'datetime-local':
+ return variable_get('date_format_html_datetime', 'Y-m-d\TH:i:sO');
+ default:
+ return $element['#date_date_format'];
+ }
+ break;
+ case 'time':
+ switch ($element['#date_time_element']) {
+ case 'time':
+ return variable_get('date_format_html_time', 'H:i:s');
+ default:
+ return $element['#date_time_format'];
+ }
+ break;
}
}
/**
- * Renders a month name for display.
+ * Creates an example for a date format.
*
- * Callback for drupal_map_assoc() within form_process_date().
+ * This is centralized for a consistent method of creating
+ * these examples.
*/
-function map_month($month) {
- $months = &drupal_static(__FUNCTION__, array(
- 1 => 'Jan',
- 2 => 'Feb',
- 3 => 'Mar',
- 4 => 'Apr',
- 5 => 'May',
- 6 => 'Jun',
- 7 => 'Jul',
- 8 => 'Aug',
- 9 => 'Sep',
- 10 => 'Oct',
- 11 => 'Nov',
- 12 => 'Dec',
- ));
- return t($months[$month]);
+function datetime_format_example($format) {
+ $date = &drupal_static(__FUNCTION__);
+ if (empty($date)) {
+ $date = new DrupalDateTime();
+ }
+ return $date->format($format);
}
/**
diff --git a/core/includes/theme.inc b/core/includes/theme.inc
index d2fe902..15bede8 100644
--- a/core/includes/theme.inc
+++ b/core/includes/theme.inc
@@ -3100,6 +3100,9 @@ function drupal_common_theme() {
'date' => array(
'render element' => 'element',
),
+ 'form_datetime' => array(
+ 'render element' => 'element',
+ ),
'exposed_filters' => array(
'render element' => 'form',
),
diff --git a/core/lib/Drupal/Component/Datetime/DateTimePlus.php b/core/lib/Drupal/Component/Datetime/DateTimePlus.php
new file mode 100644
index 0000000..8571cc8
--- /dev/null
+++ b/core/lib/Drupal/Component/Datetime/DateTimePlus.php
@@ -0,0 +1,734 @@
+ 2014, 'month => 4).
+ * Defaults to 'now'.
+ * @param mixed $timezone
+ * PHP DateTimeZone object, string or NULL allowed.
+ * Defaults to NULL.
+ * @param string $format
+ * PHP date() type format for parsing the input. This is recommended
+ * for specialized input with a known format. If provided the
+ * date will be created using the createFromFormat() method.
+ * Defaults to NULL.
+ * @see http://us3.php.net/manual/en/datetime.createfromformat.php
+ * @param array $settings
+ * - validate_format: (optional) Boolean choice to validate the
+ * created date using the input format. The format used in
+ * createFromFormat() allows slightly different values than format().
+ * Using an input format that works in both functions makes it
+ * possible to a validation step to confirm that the date created
+ * from a format string exactly matches the input. This option
+ * indicates the format can be used for validation. Defaults to TRUE.
+ * - langcode: (optional) String two letter language code to construct
+ * the locale string by the intlDateFormatter class. Used to control
+ * the result of the format() method if that class is available.
+ * Defaults to NULL.
+ * - country: (optional) String two letter country code to construct
+ * the locale string by the intlDateFormatter class. Used to control
+ * the result of the format() method if that class is available.
+ * Defaults to NULL.
+ * - calendar: (optional) String calendar name to use for the date.
+ * Defaults to DateTimePlus::CALENDAR.
+ * - debug: (optional) Boolean choice to leave debug values in the
+ * date object for debugging purposes. Defaults to FALSE.
+ */
+ public function __construct($time = 'now', $timezone = NULL, $format = NULL, $settings = array()) {
+
+ // Unpack settings.
+ $this->validateFormat = !empty($settings['validate_format']) ? $settings['validate_format'] : TRUE;
+ $this->langcode = !empty($settings['langcode']) ? $settings['langcode'] : NULL;
+ $this->country = !empty($settings['country']) ? $settings['country'] : NULL;
+ $this->calendar = !empty($settings['calendar']) ? $settings['calendar'] : static::CALENDAR;
+
+ // Store the original input so it is available for validation.
+ $this->inputTimeRaw = $time;
+ $this->inputTimeZoneRaw = $timezone;
+ $this->inputFormatRaw = $format;
+
+ // Massage the input values as necessary.
+ $this->prepareTime($time);
+ $this->prepareTimezone($timezone);
+ $this->prepareFormat($format);
+
+ // Create a date as a clone of an input DateTime object.
+ if ($this->inputIsObject()) {
+ $this->constructFromObject();
+ }
+
+ // Create date from array of date parts.
+ elseif ($this->inputIsArray()) {
+ $this->constructFromArray();
+ }
+
+ // Create a date from a Unix timestamp.
+ elseif ($this->inputIsTimestamp()) {
+ $this->constructFromTimestamp();
+ }
+
+ // Create a date from a time string and an expected format.
+ elseif ($this->inputIsFormat()) {
+ $this->constructFromFormat();
+ }
+
+ // Create a date from any other input.
+ else {
+ $this->constructFallback();
+ }
+
+ // Clean up the error messages.
+ $this->checkErrors();
+ $this->errors = array_unique($this->errors);
+
+ // Now that we've validated the input, clean up the extra values.
+ if (empty($settings['debug'])) {
+ unset(
+ $this->inputTimeRaw,
+ $this->inputTimeAdjusted,
+ $this->inputTimeZoneRaw,
+ $this->inputTimeZoneAdjusted,
+ $this->inputFormatRaw,
+ $this->inputFormatAdjusted,
+ $this->validateFormat
+ );
+ }
+
+ }
+
+ /**
+ * Implements __toString() for dates.
+ *
+ * The base DateTime class does not implement this.
+ *
+ * @see https://bugs.php.net/bug.php?id=62911
+ * @see http://www.serverphorums.com/read.php?7,555645
+ */
+ public function __toString() {
+ $format = static::FORMAT;
+ return $this->format($format) . ' ' . $this->getTimeZone()->getName();
+ }
+
+ /**
+ * Prepares the input time value.
+ *
+ * Changes the input value before trying to use it, if necessary.
+ * Can be overridden to handle special cases.
+ *
+ * @param mixed $time
+ * An input value, which could be a timestamp, a string,
+ * or an array of date parts.
+ */
+ protected function prepareTime($time) {
+ $this->inputTimeAdjusted = $time;
+ }
+
+ /**
+ * Prepares the input timezone value.
+ *
+ * Changes the timezone before trying to use it, if necessary.
+ * Most imporantly, makes sure there is a valid timezone
+ * object before moving further.
+ *
+ * @param mixed $timezone
+ * Either a timezone name or a timezone object or NULL.
+ */
+ protected function prepareTimezone($timezone) {
+ // If the input timezone is a valid timezone object, use it.
+ if ($timezone instanceOf \DateTimezone) {
+ $timezone_adjusted = $timezone;
+ }
+
+ // When the passed-in time is a DateTime object with its own
+ // timezone, try to use the date's timezone.
+ elseif (empty($timezone) && $this->inputTimeAdjusted instanceOf \DateTime) {
+ $timezone_adjusted = $this->inputTimeAdjusted->getTimezone();
+ }
+
+ // Allow string timezone input, and create a timezone from it.
+ elseif (!empty($timezone) && is_string($timezone)) {
+ $timezone_adjusted = new \DateTimeZone($timezone);
+ }
+
+ // Default to the system timezone when not explicitly provided.
+ // If the system timezone is missing, use 'UTC'.
+ if (empty($timezone_adjusted) || !$timezone_adjusted instanceOf \DateTimezone) {
+ $system_timezone = date_default_timezone_get();
+ $timezone_name = !empty($system_timezone) ? $system_timezone : 'UTC';
+ $timezone_adjusted = new \DateTimeZone($timezone_name);
+ }
+
+ // We are finally certain that we have a usable timezone.
+ $this->inputTimeZoneAdjusted = $timezone_adjusted;
+ }
+
+ /**
+ * Prepares the input format value.
+ *
+ * Changes the input format before trying to use it, if necessary.
+ * Can be overridden to handle special cases.
+ *
+ * @param string $format
+ * A PHP format string.
+ */
+ protected function prepareFormat($format) {
+ $this->inputFormatAdjusted = $format;
+ }
+
+ /**
+ * Checks whether input is a DateTime object.
+ *
+ * @return boolean
+ * TRUE if the input time is a DateTime object.
+ */
+ public function inputIsObject() {
+ return $this->inputTimeAdjusted instanceOf \DateTime;
+ }
+
+ /**
+ * Creates a date object from an input date object.
+ */
+ protected function constructFromObject() {
+ try {
+ $this->inputTimeAdjusted = $this->inputTimeAdjusted->format(static::FORMAT);
+ parent::__construct($this->inputTimeAdjusted, $this->inputTimeZoneAdjusted);
+ }
+ catch (\Exception $e) {
+ $this->errors[] = $e->getMessage();
+ }
+ }
+
+ /**
+ * Checks whether input time seems to be a timestamp.
+ *
+ * Providing an input format will prevent ISO values without separators
+ * from being mis-interpreted as timestamps. Providing a format can also
+ * avoid interpreting a value like '2010' with a format of 'Y' as a
+ * timestamp. The 'U' format indicates this is a timestamp.
+ *
+ * @return boolean
+ * TRUE if the input time is a timestamp.
+ */
+ public function inputIsTimestamp() {
+ return is_numeric($this->inputTimeAdjusted) && (empty($this->inputFormatAdjusted) || $this->inputFormatAdjusted == 'U');
+ }
+
+ /**
+ * Creates a date object from timestamp input.
+ *
+ * The timezone of a timestamp is always UTC. The timezone for a
+ * timestamp indicates the timezone used by the format() method.
+ */
+ protected function constructFromTimestamp() {
+ try {
+ parent::__construct('', $this->inputTimeZoneAdjusted);
+ $this->setTimestamp($this->inputTimeAdjusted);
+ }
+ catch (\Exception $e) {
+ $this->errors[] = $e->getMessage();
+ }
+ }
+
+ /**
+ * Checks if input is an array of date parts.
+ *
+ * @return boolean
+ * TRUE if the input time is a DateTime object.
+ */
+ public function inputIsArray() {
+ return is_array($this->inputTimeAdjusted);
+ }
+
+ /**
+ * Creates a date object from an array of date parts.
+ *
+ * Converts the input value into an ISO date, forcing a full ISO
+ * date even if some values are missing.
+ */
+ protected function constructFromArray() {
+ try {
+ parent::__construct('', $this->inputTimeZoneAdjusted);
+ $this->inputTimeAdjusted = static::prepareArray($this->inputTimeAdjusted, TRUE);
+ if (static::checkArray($this->inputTimeAdjusted)) {
+ // Even with validation, we can end up with a value that the
+ // parent class won't handle, like a year outside the range
+ // of -9999 to 9999, which will pass checkdate() but
+ // fail to construct a date object.
+ $this->inputTimeAdjusted = static::arrayToISO($this->inputTimeAdjusted);
+ parent::__construct($this->inputTimeAdjusted, $this->inputTimeZoneAdjusted);
+ }
+ else {
+ throw new \Exception('The array contains invalid values.');
+ }
+ }
+ catch (\Exception $e) {
+ $this->errors[] = $e->getMessage();
+ }
+ }
+
+ /**
+ * Checks if input is a string with an expected format.
+ *
+ * @return boolean
+ * TRUE if the input time is a string with an expected format.
+ */
+ public function inputIsFormat() {
+ return is_string($this->inputTimeAdjusted) && !empty($this->inputFormatAdjusted);
+ }
+
+ /**
+ * Creates a date object from an input format.
+ */
+ protected function constructFromFormat() {
+ // Tries to create a date from the format and use it if possible.
+ // A regular try/catch won't work right here, if the value is
+ // invalid it doesn't return an exception.
+ try {
+ parent::__construct('', $this->inputTimeZoneAdjusted);
+ $date = parent::createFromFormat($this->inputFormatAdjusted, $this->inputTimeAdjusted, $this->inputTimeZoneAdjusted);
+ if (!$date instanceOf \DateTime) {
+ throw new \Exception('The date cannot be created from a format.');
+ }
+ else {
+ $this->setTimestamp($date->getTimestamp());
+ $this->setTimezone($date->getTimezone());
+
+ try {
+ // The createFromFormat function is forgiving, it might
+ // create a date that is not exactly a match for the provided
+ // value, so test for that. For instance, an input value of
+ // '11' using a format of Y (4 digits) gets created as
+ // '0011' instead of '2011'.
+ // Use the parent::format() because we do not want to use
+ // the IntlDateFormatter here.
+ if ($this->validateFormat && parent::format($this->inputFormatAdjusted) != $this->inputTimeRaw) {
+ throw new \Exception('The created date does not match the input value.');
+ }
+ }
+ catch (\Exception $e) {
+ $this->errors[] = $e->getMessage();
+ }
+ }
+ }
+ catch (\Exception $e) {
+ $this->errors[] = $e->getMessage();
+ }
+ }
+
+ /**
+ * Creates a date when none of the other methods are appropriate.
+ *
+ * Fallback construction for values that don't match any of the
+ * other patterns. Lets the parent dateTime attempt to turn this string
+ * into a valid date.
+ */
+ protected function constructFallback() {
+
+ try {
+ // One last test for invalid input before we try to construct
+ // a date. If the input contains totally bogus information
+ // it will blow up badly if we pass it to the constructor.
+ // The date_parse() function will tell us if the input
+ // makes sense.
+ if (!empty($this->inputTimeAdjusted)) {
+ $test = date_parse($this->inputTimeAdjusted);
+ if (!empty($test['errors'])) {
+ $this->errors[] = $test['errors'];
+ }
+ }
+
+ if (empty($this->errors)) {
+ @parent::__construct($this->inputTimeAdjusted, $this->inputTimeZoneAdjusted);
+ }
+ }
+ catch (\Exception $e) {
+ $this->errors[] = $e->getMessage();
+ }
+ }
+
+ /**
+ * Examines getLastErrors() to see what errors to report.
+ *
+ * Two kinds of errors are important: anything that DateTime
+ * considers an error, and also a warning that the date was invalid.
+ * PHP creates a valid date from invalid data with only a warning,
+ * 2011-02-30 becomes 2011-03-03, for instance, but we don't want that.
+ *
+ * @see http://us3.php.net/manual/en/time.getlasterrors.php
+ */
+ public function checkErrors() {
+ $errors = $this->getLastErrors();
+ if (!empty($errors['errors'])) {
+ $this->errors += $errors['errors'];
+ }
+ // Most warnings are messages that the date could not be parsed
+ // which causes it to be altered. For validation purposes, a warning
+ // as bad as an error, because it means the constructed date does
+ // not match the input value.
+ if (!empty($errors['warnings'])) {
+ $this->errors[] = 'The date is invalid.';
+ }
+ }
+
+ /**
+ * Detects if there were errors in the processing of this date.
+ */
+ public function hasErrors() {
+ return (boolean) count($this->errors);
+ }
+
+ /**
+ * Retrieves error messages.
+ *
+ * Public function to return the error messages.
+ */
+ public function getErrors() {
+ return $this->errors;
+ }
+
+ /**
+ * Creates an ISO date from an array of values.
+ *
+ * @param array $array
+ * An array of date values keyed by date part.
+ * @param bool $force_valid_date
+ * (optional) Whether to force a full date by filling in missing
+ * values. Defaults to FALSE.
+ *
+ * @return string
+ * The date as an ISO string.
+ */
+ public static function arrayToISO($array, $force_valid_date = FALSE) {
+ $array = static::prepareArray($array, $force_valid_date);
+ $input_time = '';
+ if ($array['year'] !== '') {
+ $input_time = static::datePad(intval($array['year']), 4);
+ if ($force_valid_date || $array['month'] !== '') {
+ $input_time .= '-' . static::datePad(intval($array['month']));
+ if ($force_valid_date || $array['day'] !== '') {
+ $input_time .= '-' . static::datePad(intval($array['day']));
+ }
+ }
+ }
+ if ($array['hour'] !== '') {
+ $input_time .= $input_time ? 'T' : '';
+ $input_time .= static::datePad(intval($array['hour']));
+ if ($force_valid_date || $array['minute'] !== '') {
+ $input_time .= ':' . static::datePad(intval($array['minute']));
+ if ($force_valid_date || $array['second'] !== '') {
+ $input_time .= ':' . static::datePad(intval($array['second']));
+ }
+ }
+ }
+ return $input_time;
+ }
+
+ /**
+ * Creates a complete array from a possibly incomplete array of date parts.
+ *
+ * @param array $array
+ * An array of date values keyed by date part.
+ * @param bool $force_valid_date
+ * (optional) Whether to force a valid date by filling in missing
+ * values with valid values or just to use empty values instead.
+ * Defaults to FALSE.
+ *
+ * @return array
+ * A complete array of date parts.
+ */
+ public static function prepareArray($array, $force_valid_date = FALSE) {
+ if ($force_valid_date) {
+ $now = new \DateTime();
+ $array += array(
+ 'year' => $now->format('Y'),
+ 'month' => 1,
+ 'day' => 1,
+ 'hour' => 0,
+ 'minute' => 0,
+ 'second' => 0,
+ );
+ }
+ else {
+ $array += array(
+ 'year' => '',
+ 'month' => '',
+ 'day' => '',
+ 'hour' => '',
+ 'minute' => '',
+ 'second' => '',
+ );
+ }
+ return $array;
+ }
+
+ /**
+ * Checks that arrays of date parts will create a valid date.
+ *
+ * Checks that an array of date parts has a year, month, and day,
+ * and that those values create a valid date. If time is provided,
+ * verifies that the time values are valid. Sort of an
+ * equivalent to checkdate().
+ *
+ * @param array $array
+ * An array of datetime values keyed by date part.
+ *
+ * @return boolean
+ * TRUE if the datetime parts contain valid values, otherwise FALSE.
+ */
+ public static function checkArray($array) {
+ $valid_date = FALSE;
+ $valid_time = TRUE;
+ // Check for a valid date using checkdate(). Only values that
+ // meet that test are valid.
+ if (array_key_exists('year', $array) && array_key_exists('month', $array) && array_key_exists('day', $array)) {
+ if (@checkdate($array['month'], $array['day'], $array['year'])) {
+ $valid_date = TRUE;
+ }
+ }
+ // Testing for valid time is reversed. Missing time is OK,
+ // but incorrect values are not.
+ foreach (array('hour', 'minute', 'second') as $key) {
+ if (array_key_exists($key, $array)) {
+ $value = $array[$key];
+ switch ($value) {
+ case 'hour':
+ if (!preg_match('/^([1-2][0-3]|[01]?[0-9])$/', $value)) {
+ $valid_time = FALSE;
+ }
+ break;
+ case 'minute':
+ case 'second':
+ default:
+ if (!preg_match('/^([0-5][0-9]|[0-9])$/', $value)) {
+ $valid_time = FALSE;
+ }
+ break;
+ }
+ }
+ }
+ return $valid_date && $valid_time;
+ }
+
+ /**
+ * Pads date parts with zeros.
+ *
+ * Helper function for a task that is often required when working with dates.
+ *
+ * @param int $value
+ * The value to pad.
+ * @param int $size
+ * (optional) Size expected, usually 2 or 4. Defaults to 2.
+ *
+ * @return string
+ * The padded value.
+ */
+ public static function datePad($value, $size = 2) {
+ return sprintf("%0" . $size . "d", $value);
+ }
+
+
+ /**
+ * Tests whether the IntlDateFormatter can be used.
+ */
+ public function canUseIntl() {
+ return class_exists('IntlDateFormatter') && !empty($this->calendar) && !empty($this->langcode) && !empty($this->country);
+ }
+
+ /**
+ * Formats the date for display.
+ *
+ * Uses the IntlDateFormatter to display the format, if possible.
+ * Adds an optional array of settings that provides the information
+ * the IntlDateFormatter will need.
+ *
+ * @param string $format
+ * A format string using either PHP's date() or the
+ * IntlDateFormatter() format.
+ * @param array $settings
+ * - format_string_type: (optional) DateTimePlus::PHP or
+ * DateTimePlus::INTL. Identifies the pattern used by the format
+ * string. When using the Intl formatter, the format string must
+ * use the Intl pattern, which is different from the pattern used
+ * by the DateTime format function. Defaults to DateTimePlus::PHP.
+ * - timezone: (optional) String timezone name. Defaults to the timezone
+ * of the date object.
+ * - langcode: (optional) String two letter language code to construct the
+ * locale string by the intlDateFormatter class. Used to control the
+ * result of the format() method if that class is available. Defaults
+ * to NULL.
+ * - country: (optional) String two letter country code to construct the
+ * locale string by the intlDateFormatter class. Used to control the
+ * result of the format() method if that class is available. Defaults
+ * to NULL.
+ * - calendar: (optional) String calendar name to use for the date,
+ * Defaults to DateTimePlus::CALENDAR.
+ * - date_type: (optional) Integer date type to use in the formatter,
+ * defaults to IntlDateFormatter::FULL.
+ * - time_type: (optional) Integer date type to use in the formatter,
+ * defaults to IntlDateFormatter::FULL.
+ * - lenient: (optional) Boolean choice of whether or not to use lenient
+ * processing in the intl formatter. Defaults to FALSE;
+ *
+ * @return string
+ * The formatted value of the date.
+ */
+ public function format($format, $settings = array()) {
+
+ // If there were construction errors, we can't format the date.
+ if ($this->hasErrors()) {
+ return;
+ }
+
+ $format_string_type = isset($settings['format_string_type']) ? $settings['format_string_type'] : static::PHP;
+ $langcode = !empty($settings['langcode']) ? $settings['langcode'] : $this->langcode;
+ $country = !empty($settings['country']) ? $settings['country'] : $this->country;
+ $calendar = !empty($settings['calendar']) ? $settings['calendar'] : $this->calendar;
+ $timezone = !empty($settings['timezone']) ? $settings['timezone'] : $this->getTimezone()->getName();
+ $lenient = !empty($settings['lenient']) ? $settings['lenient'] : FALSE;
+
+ // Format the date and catch errors.
+ try {
+
+ // If we have what we need to use the IntlDateFormatter, do so.
+ if ($this->canUseIntl() && $format_string_type == static::INTL) {
+
+ // Construct the $locale variable needed by the IntlDateFormatter.
+ $locale = $langcode . '_' . $country;
+
+ // If we have information about a calendar, add it.
+ if (!empty($calendar) && $calendar != static::CALENDAR) {
+ $locale .= '@calendar=' . $calendar;
+ }
+
+ // If we're working with a non-gregorian calendar, indicate that.
+ $calendar_type = \IntlDateFormatter::GREGORIAN;
+ if ($calendar != SELF::CALENDAR) {
+ $calendar_type = \IntlDateFormatter::TRADITIONAL;
+ }
+
+ $date_type = !empty($settings['date_type']) ? $settings['date_type'] : \IntlDateFormatter::FULL;
+ $time_type = !empty($settings['time_type']) ? $settings['time_type'] : \IntlDateFormatter::FULL;
+ $formatter = new \IntlDateFormatter($locale, $date_type, $time_type, $timezone, $calendar_type);
+ $formatter->setLenient($lenient);
+ $value = $formatter->format($format);
+ }
+
+ // Otherwise, use the parent method.
+ else {
+ $value = parent::format($format);
+ }
+ }
+ catch (\Exception $e) {
+ $this->errors[] = $e->getMessage();
+ }
+ return $value;
+ }
+}
diff --git a/core/lib/Drupal/Core/Datetime/DrupalDateTime.php b/core/lib/Drupal/Core/Datetime/DrupalDateTime.php
new file mode 100644
index 0000000..775e668
--- /dev/null
+++ b/core/lib/Drupal/Core/Datetime/DrupalDateTime.php
@@ -0,0 +1,163 @@
+ 2014, 'month => 4).
+ * Defaults to 'now'.
+ * @param mixed $timezone
+ * PHP DateTimeZone object, string or NULL allowed.
+ * Defaults to NULL.
+ * @param string $format
+ * PHP date() type format for parsing the input. This is recommended
+ * to use things like negative years, which php's parser fails on, or
+ * any other specialized input with a known format. If provided the
+ * date will be created using the createFromFormat() method.
+ * Defaults to NULL.
+ * @see http://us3.php.net/manual/en/datetime.createfromformat.php
+ * @param array $settings
+ * - validate_format: (optional) Boolean choice to validate the
+ * created date using the input format. The format used in
+ * createFromFormat() allows slightly different values than format().
+ * Using an input format that works in both functions makes it
+ * possible to a validation step to confirm that the date created
+ * from a format string exactly matches the input. This option
+ * indicates the format can be used for validation. Defaults to TRUE.
+ * - langcode: (optional) String two letter language code to construct
+ * the locale string by the intlDateFormatter class. Used to control
+ * the result of the format() method if that class is available.
+ * Defaults to NULL.
+ * - country: (optional) String two letter country code to construct
+ * the locale string by the intlDateFormatter class. Used to control
+ * the result of the format() method if that class is available.
+ * Defaults to NULL.
+ * - calendar: (optional) String calendar name to use for the date.
+ * Defaults to DateTimePlus::CALENDAR.
+ * - debug: (optional) Boolean choice to leave debug values in the
+ * date object for debugging purposes. Defaults to FALSE.
+ */
+ public function __construct($time = 'now', $timezone = NULL, $format = NULL, $settings = array()) {
+
+ // We can set the langcode and country using Drupal values.
+ $settings['langcode'] = !empty($settings['langcode']) ? $settings['langcode'] : language(LANGUAGE_TYPE_INTERFACE)->langcode;
+ $settings['country'] = !empty($settings['country']) ? $settings['country'] : variable_get('site_default_country');
+
+ // Instantiate the parent class.
+ parent::__construct($time, $timezone, $format, $settings);
+
+ }
+
+ /**
+ * Overrides prepareTimezone().
+ *
+ * Override basic component timezone handling to use Drupal's
+ * knowledge of the preferred user timezone.
+ */
+ protected function prepareTimezone($timezone) {
+ $user_timezone = drupal_get_user_timezone();
+ if (empty($timezone) && !empty($user_timezone)) {
+ $timezone = $user_timezone;
+ }
+ parent::prepareTimezone($timezone);
+ }
+
+ /**
+ * Overrides format().
+ *
+ * Uses the IntlDateFormatter to display the format, if possible.
+ * Adds an optional array of settings that provides the information
+ * the IntlDateFormatter will need.
+ *
+ * @param string $format
+ * A format string using either PHP's date() or the
+ * IntlDateFormatter() format.
+ * @param array $settings
+ * - format_string_type: (optional) DateTimePlus::PHP or
+ * DateTimePlus::INTL. Identifies the pattern used by the format
+ * string. When using the Intl formatter, the format string must
+ * use the Intl pattern, which is different from the pattern used
+ * by the DateTime format function. Defaults to DateTimePlus::PHP.
+ * - timezone: (optional) String timezone name. Defaults to the timezone
+ * of the date object.
+ * - langcode: (optional) String two letter language code to construct the
+ * locale string by the intlDateFormatter class. Used to control the
+ * result of the format() method if that class is available. Defaults
+ * to NULL.
+ * - country: (optional) String two letter country code to construct the
+ * locale string by the intlDateFormatter class. Used to control the
+ * result of the format() method if that class is available. Defaults
+ * to NULL.
+ * - calendar: (optional) String calendar name to use for the date,
+ * Defaults to DateTimePlus::CALENDAR.
+ * - date_type: (optional) Integer date type to use in the formatter,
+ * defaults to IntlDateFormatter::FULL.
+ * - time_type: (optional) Integer date type to use in the formatter,
+ * defaults to IntlDateFormatter::FULL.
+ * - lenient: (optional) Boolean choice of whether or not to use lenient
+ * processing in the intl formatter. Defaults to FALSE;
+ *
+ * @return string
+ * The formatted value of the date.
+ */
+ public function format($format, $settings = array()) {
+
+ $format_string_type = isset($settings['format_string_type']) ? $settings['format_string_type'] : static::PHP;
+
+ $settings['langcode'] = !empty($settings['langcode']) ? $settings['langcode'] : $this->langcode;
+ $settings['country'] = !empty($settings['country']) ? $settings['country'] : $this->country;
+
+ // Format the date and catch errors.
+ try {
+
+ // If we have what we need to use the IntlDateFormatter, do so.
+ if ($this->canUseIntl() && $format_string_type == parent::INTL) {
+ $value = parent::format($format, $settings);
+ }
+
+ // Otherwise, use the default Drupal method.
+ else {
+
+ // Encode markers that should be translated. 'A' becomes
+ // '\xEF\AA\xFF'. xEF and xFF are invalid UTF-8 sequences,
+ // and we assume they are not in the input string.
+ // Paired backslashes are isolated to prevent errors in
+ // read-ahead evaluation. The read-ahead expression ensures that
+ // A matches, but not \A.
+ $format = preg_replace(array('/\\\\\\\\/', '/(?errors[] = $e->getMessage();
+ }
+ return $value;
+ }
+}
diff --git a/core/lib/Drupal/Core/TypedData/Type/Date.php b/core/lib/Drupal/Core/TypedData/Type/Date.php
index 07767e9..3c0f3a9 100644
--- a/core/lib/Drupal/Core/TypedData/Type/Date.php
+++ b/core/lib/Drupal/Core/TypedData/Type/Date.php
@@ -7,16 +7,17 @@
namespace Drupal\Core\TypedData\Type;
+use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\TypedData\TypedDataInterface;
-use DateTime;
use InvalidArgumentException;
/**
* The date data type.
*
- * The plain value of a date is an instance of the DateTime class. For setting
- * the value an instance of the DateTime class, any string supported by
- * DateTime::__construct(), or a timestamp as integer may be passed.
+ * The plain value of a date is an instance of the DrupalDateTime class. For setting
+ * the value any value supported by the __construct() of the DrupalDateTime
+ * class will work, including a DateTime object, a timestamp, a string
+ * date, or an array of date parts.
*/
class Date extends TypedData implements TypedDataInterface {
@@ -31,18 +32,17 @@ class Date extends TypedData implements TypedDataInterface {
* Implements TypedDataInterface::setValue().
*/
public function setValue($value) {
- if ($value instanceof DateTime || !isset($value)) {
+
+ // Don't try to create a date from an empty value.
+ // It would default to the current time.
+ if (!isset($value)) {
$this->value = $value;
}
- // Treat integer values as timestamps, even if supplied as PHP string.
- elseif ((string) (int) $value === (string) $value) {
- $this->value = new DateTime('@' . $value);
- }
- elseif (is_string($value)) {
- $this->value = new DateTime($value);
- }
else {
- throw new InvalidArgumentException("Invalid date format given.");
+ $this->value = $value instanceOf DrupalDateTime ? $value : new DrupalDateTime($value);
+ if ($this->value->hasErrors()) {
+ throw new InvalidArgumentException("Invalid date format given.");
+ }
}
}
@@ -50,7 +50,7 @@ public function setValue($value) {
* Implements TypedDataInterface::getString().
*/
public function getString() {
- return (string) $this->getValue()->format(DateTime::ISO8601);
+ return (string) $this->getValue();
}
/**
diff --git a/core/misc/datepicker.js b/core/misc/datepicker.js
new file mode 100644
index 0000000..3fef66a
--- /dev/null
+++ b/core/misc/datepicker.js
@@ -0,0 +1,29 @@
+/**
+ * Attaches the datepicker behavior to all required fields
+ */
+(function ($) {
+Drupal.behaviors.dateTime = {
+ attach: function (context, settings) {
+
+ var i = document.createElement("input");
+ i.setAttribute("type", "date");
+ if (i.type == "text") {
+ // No native date picker support? Use jQueryUI.
+ for (var id in Drupal.settings.dateTime) {
+ $(id).bind('focus', Drupal.settings.dateTime[id], function(e) {
+ if (!$(this).hasClass('date-popup-init')) {
+ var dateTime = e.data;
+ $(this)
+ .datepicker(dateTime)
+ .addClass('date-popup-init')
+ $(this).click(function(){
+ $(this).focus();
+ });
+ }
+ });
+ }
+ }
+ }
+};
+})(jQuery);
+
diff --git a/core/modules/comment/lib/Drupal/comment/CommentFormController.php b/core/modules/comment/lib/Drupal/comment/CommentFormController.php
index cead0cd..50110dc 100644
--- a/core/modules/comment/lib/Drupal/comment/CommentFormController.php
+++ b/core/modules/comment/lib/Drupal/comment/CommentFormController.php
@@ -9,6 +9,7 @@
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityFormController;
+use Drupal\Core\Datetime\DrupalDateTime;
/**
* Base for controller for comment forms.
@@ -63,7 +64,7 @@ public function form(array $form, array &$form_state, EntityInterface $comment)
if ($is_admin) {
$author = (!$comment->uid && $comment->name ? $comment->name : $comment->registered_name);
$status = (isset($comment->status) ? $comment->status : COMMENT_NOT_PUBLISHED);
- $date = (!empty($comment->date) ? $comment->date : format_date($comment->created, 'custom', 'Y-m-d H:i O'));
+ $date = (!empty($comment->date) ? $comment->date : new DrupalDateTime($comment->created));
}
else {
if ($user->uid) {
@@ -134,7 +135,7 @@ public function form(array $form, array &$form_state, EntityInterface $comment)
// Add administrative comment publishing options.
$form['author']['date'] = array(
- '#type' => 'textfield',
+ '#type' => 'datetime',
'#title' => t('Authored on'),
'#default_value' => $date,
'#maxlength' => 25,
@@ -236,7 +237,8 @@ public function validate(array $form, array &$form_state) {
$account = user_load_by_name($form_state['values']['name']);
$form_state['values']['uid'] = $account ? $account->uid : 0;
- if ($form_state['values']['date'] && strtotime($form_state['values']['date']) === FALSE) {
+ $date = $form_state['values']['date'];
+ if (!$date instanceOf DrupalDateTime || $date->hasErrors()) {
form_set_error('date', t('You have to specify a valid date.'));
}
if ($form_state['values']['name'] && !$form_state['values']['is_anonymous'] && !$account) {
@@ -271,7 +273,7 @@ public function submit(array $form, array &$form_state) {
if (empty($comment->date)) {
$comment->date = 'now';
}
- $comment->created = strtotime($comment->date);
+ $comment->created = $comment->date->getTimestamp();
$comment->changed = REQUEST_TIME;
// If the comment was posted by a registered user, assign the author's ID.
diff --git a/core/modules/field/modules/datetime/datetime.info b/core/modules/field/modules/datetime/datetime.info
new file mode 100644
index 0000000..5064609
--- /dev/null
+++ b/core/modules/field/modules/datetime/datetime.info
@@ -0,0 +1,6 @@
+name = Date
+description = A simple date/time field.
+package = Core
+version = VERSION
+core = 8.x
+dependencies[] = field
\ No newline at end of file
diff --git a/core/modules/field/modules/datetime/datetime.install b/core/modules/field/modules/datetime/datetime.install
new file mode 100644
index 0000000..910cff9
--- /dev/null
+++ b/core/modules/field/modules/datetime/datetime.install
@@ -0,0 +1,31 @@
+ 'The date value',
+ 'type' => 'varchar',
+ 'length' => 20,
+ 'not null' => FALSE,
+ );
+ $indexes = array(
+ 'value' => array('value'),
+ );
+ return array('columns' => $db_columns, 'indexes' => $indexes);
+}
+
+// @TODO
+// Update any existing fields of the type 'datetime' to 'datetimeold',
+// then add upgrade path in Date module for those types so we can
+// re-use the field type name for a new field in core.
+function datetime_install() {
+
+}
\ No newline at end of file
diff --git a/core/modules/field/modules/datetime/datetime.module b/core/modules/field/modules/datetime/datetime.module
new file mode 100644
index 0000000..08b363f
--- /dev/null
+++ b/core/modules/field/modules/datetime/datetime.module
@@ -0,0 +1,171 @@
+ array(
+ 'label' => 'Date',
+ 'description' => t('Create and store simple date values.'),
+ 'settings' => array(
+ 'granularity' => 'datetime',
+ ),
+ 'instance_settings' => array(
+ 'default_value' => 'now',
+ ),
+ 'default_widget' => 'datetime_datepicker',
+ 'default_formatter' => 'datetime_default',
+ 'default_token_formatter' => 'datetime_plain',
+ 'field item class' => '\Drupal\datetime\Type\DateTimeItem',
+ ),
+ );
+}
+
+/**
+ * Implements hook_field_settings_form().
+ */
+function datetime_field_settings_form($field, $instance, $has_data) {
+ $settings = $field['settings'];
+
+ $form['granularity'] = array(
+ '#type' => 'select',
+ '#title' => t('Date type'),
+ '#description' => t('Choose the type of date to create.'),
+ '#default_value' => $settings['granularity'],
+ '#options' => array(
+ 'datetime' => t('Date and time'),
+ 'date' => t('Date only'),
+ ),
+ );
+ return $form;
+}
+
+/**
+ * Implements hook_field_instance_settings_form().
+ */
+function datetime_field_instance_settings_form($field, $instance) {
+ $widget = $instance['widget'];
+ $settings = $instance['settings'];
+ $widget_settings = $instance['widget']['settings'];
+
+ $form['default_value'] = array(
+ '#type' => 'select',
+ '#title' => t('Default date'),
+ '#description' => t('Set a default value for this date.'),
+ '#default_value' => $settings['default_value'],
+ '#options' => array('blank' => t('No default value'), 'now' => t('The current date')),
+ '#weight' => 1,
+ );
+
+ return $form;
+}
+
+/**
+ * Validation callback for the datetime form element.
+ *
+ * The date has already been validated by the datetime form type
+ * validator and transformed to an date string. We just need to
+ * convert the date back to a the right timezone and format for storage.
+ */
+function datetime_widget_validate(&$element, &$form_state) {
+ if (!form_get_errors()) {
+ $input_exists = FALSE;
+ $input = drupal_array_get_nested_value($form_state['values'], $element['#parents'], $input_exists);
+ if ($input_exists) {
+ // The date should have been returned to a date object at this
+ // point by datetime_validate(), which runs before this.
+ if (!empty($input['value'])) {
+ $date = $input['value'];
+ if ($date instanceOf DrupalDateTime && !$date->hasErrors()) {
+
+ // If this is a date-only field, change the format
+ // and set it to midnight so the timezone conversion can be reversed.
+ if ($element['value']['#date_time_element'] == 'none') {
+ $date->setTime(0, 0, 0);
+ }
+ // Adjust the date for storage.
+ $date->setTimezone(new \DateTimezone(DATETIME_STORAGE_TIMEZONE));
+ $value = $date->format($element['value']['#date_storage_format']);
+ form_set_value($element['value'], $value, $form_state);
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Implements hook_field_load().
+ *
+ * The function generates a Date object for each field early so that it is
+ * cached in the field cache. This avoids the need to generate the
+ * object later. The date will be retrieved in UTC, the local timezone
+ * adjustment must be made in realtime, based on the preferences of the
+ * site and user.
+ */
+function datetime_field_load($entity_type, $entities, $field, $instances, $langcode, &$items) {
+
+ // Load the stored date values and create date objects for caching.
+ foreach ($entities as $id => $entity) {
+ foreach ($items[$id] as $delta => $item) {
+ $items[$id][$delta]['date'] = NULL;
+ $value = isset($item['value']) ? $item['value'] : NULL;
+ if (!empty($value)) {
+ $storage_format = $field['settings']['granularity'] == 'date' ? DATETIME_DATE_STORAGE_FORMAT: DATETIME_DEFAULT_STORAGE_FORMAT;
+ $date = new DrupalDateTime($value, DATETIME_STORAGE_TIMEZONE, $storage_format);
+ if ($date instanceOf DrupalDateTime && !$date->hasErrors()) {
+ $items[$id][$delta]['date'] = $date;
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Sets a default value for an empty date field.
+ *
+ * Callback for $instance['default_value_function'], as implemented
+ * by Drupal\datetime\Plugin\field\widget\DateTimeDatepicker.
+ */
+function datetime_default_value($entity_type, $entity, $field, $instance, $langcode) {
+
+ $value = '';
+ $date = '';
+ if ($instance['settings']['default_value'] == 'now') {
+ // A default value should be in the format and timezone used
+ // for date storage.
+ $date = new DrupalDateTime('now', DATETIME_STORAGE_TIMEZONE);
+ $storage_format = $field['settings']['granularity'] == 'date' ? DATETIME_DATE_STORAGE_FORMAT: DATETIME_DEFAULT_STORAGE_FORMAT;
+ $value = $date->format($storage_format);
+ }
+
+ // We only provide a default value for the first item, as do
+ // all fields. Otherwise there is no way to clear out unwanted
+ // values on multiple value fields.
+ $item = array();
+ $item[0]['value'] = $value;
+ $item[0]['date'] = $date;
+
+ return $item;
+}
diff --git a/core/modules/field/modules/datetime/datetime.views.inc b/core/modules/field/modules/datetime/datetime.views.inc
new file mode 100644
index 0000000..0fd2048
--- /dev/null
+++ b/core/modules/field/modules/datetime/datetime.views.inc
@@ -0,0 +1,28 @@
+ $item) {
+
+ $output = '';
+ if (!empty($item['date'])) {
+ // The date was created and verified during field_load(), so
+ // it's safe to use without further inspection.
+ $date = $item['date'];
+ $date->setTimeZone(timezone_open(drupal_get_user_timezone()));
+ if ($this->field['settings']['granularity'] == 'date') {
+ // A date without time will pick up the current time,
+ // reset it to midnight.
+ $date->setTime(0, 0, 0);
+ }
+ $output = $this->dateFormat($date);
+ }
+ $elements[$delta] = array('#markup' => $output);
+ }
+
+ return $elements;
+
+ }
+
+ /**
+ * Format a formatted date value.
+ *
+ * @param object $date
+ * A date object.
+ *
+ * @return string
+ * Returns a date formatted with the formatter's chosen format.
+ */
+ function dateFormat($date) {
+ $format_type = $this->getSetting('format_type');
+ return format_date($date->getTimestamp(), $format_type);
+ }
+
+ /**
+ * Implements Drupal\field\Plugin\Type\Formatter\FormatterInterface::settingsForm().
+ */
+ public function settingsForm(array $form, array &$form_state) {
+
+ $element = array();
+
+ $time = new DrupalDateTime();
+ $format_types = system_get_date_types();
+ if (!empty($format_types)) {
+ foreach ($format_types as $type => $type_info) {
+ $options[$type] = $type_info['title'] . ' (' . format_date($time->format('U'), $type) . ')';
+ }
+ }
+
+ $elements['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 $elements;
+ }
+
+ /**
+ * Implements Drupal\field\Plugin\Type\Formatter\FormatterInterface::settingsSummary().
+ */
+ public function settingsSummary() {
+
+ $date = new DrupalDateTime();
+ $output = array();
+ $output[] = t('Format: @display', array('@display' => $this->dateFormat($date, FALSE)));
+ return implode(' ', $output);
+
+ }
+}
diff --git a/core/modules/field/modules/datetime/lib/Drupal/datetime/Plugin/field/formatter/DatetimePlainFormatter.php b/core/modules/field/modules/datetime/lib/Drupal/datetime/Plugin/field/formatter/DatetimePlainFormatter.php
new file mode 100644
index 0000000..293d1a9
--- /dev/null
+++ b/core/modules/field/modules/datetime/lib/Drupal/datetime/Plugin/field/formatter/DatetimePlainFormatter.php
@@ -0,0 +1,45 @@
+ $item) {
+ $elements[$delta] = array('#markup' => $item['value']);
+ }
+
+ return $elements;
+
+ }
+
+}
diff --git a/core/modules/field/modules/datetime/lib/Drupal/datetime/Plugin/field/widget/DatetimeDatepicker.php b/core/modules/field/modules/datetime/lib/Drupal/datetime/Plugin/field/widget/DatetimeDatepicker.php
new file mode 100644
index 0000000..12674b8
--- /dev/null
+++ b/core/modules/field/modules/datetime/lib/Drupal/datetime/Plugin/field/widget/DatetimeDatepicker.php
@@ -0,0 +1,130 @@
+field;
+ $instance = $this->instance;
+
+ // We're nesting some sub-elements inside the parent, so we
+ // need a wrapper. We also need to add another #title attribute
+ // at the top level for ease in identifying this item in error
+ // messages. We don't want to display this title because the
+ // actual title display is handled at a higher level by the Field
+ // module.
+
+ $element['#theme_wrappers'][] = 'form_element';
+ $element['#attributes']['class'][] = 'container-inline';
+ $element['#element_validate'][] = 'datetime_widget_validate';
+
+ // Identify the type of date and time elements to use.
+ switch ($field['settings']['granularity']) {
+ case 'date':
+ $date_type = 'date';
+ $time_type = 'none';
+ $date_format = variable_get('date_format_html_date', 'Y-m-d');
+ $time_format = '';
+ $element_format = $date_format;
+ $storage_format = DATETIME_DATE_STORAGE_FORMAT;
+ break;
+ default:
+ $date_type = 'date';
+ $time_type = 'time';
+ $date_format = variable_get('date_format_html_date', 'Y-m-d');
+ $time_format = variable_get('date_format_html_time', 'H:i:s');
+ $element_format = $date_format . ' ' . $time_format;
+ $storage_format = DATETIME_DEFAULT_STORAGE_FORMAT;
+ break;
+ }
+
+ $element['value'] = array(
+ '#type' => 'datetime',
+ '#default_value' => NULL,
+ '#title' => $instance->definition['label'],
+ '#title_display' => 'invisible',
+ '#date_increment' => 1,
+ '#date_date_format'=> $date_format,
+ '#date_date_element' => $date_type,
+ '#date_date_callbacks' => array('datetime_jquery_datepicker_callback'),
+ '#date_time_format' => $time_format,
+ '#date_time_element' => $time_type,
+ '#date_time_callbacks' => array(),
+ '#date_timezone' => drupal_get_user_timezone(),
+ '#required' => $element['#required'],
+ );
+
+ // Set the storage and widget options so the validation can use them.
+ // The validator won't have access to field or instance settings.
+ $element['value']['#date_element_format'] = $element_format;
+ $element['value']['#date_storage_format'] = $storage_format;
+
+ if (!empty($items[$delta]['date'])) {
+ $date = $items[$delta]['date'];
+ // The date was created and verified during field_load(), so
+ // it's safe to use without further inspection.
+ $date->setTimezone( new \DateTimeZone($element['value']['#date_timezone']));
+ if ($field['settings']['granularity'] == 'date') {
+ // A date without time will pick up the current time,
+ // reset it to midnight.
+ $date->setTime(0, 0, 0);
+ }
+ $element['value']['#default_value'] = $date;
+ }
+ return $element;
+ }
+
+}
diff --git a/core/modules/field/modules/datetime/lib/Drupal/datetime/Type/DateTimeItem.php b/core/modules/field/modules/datetime/lib/Drupal/datetime/Type/DateTimeItem.php
new file mode 100644
index 0000000..a51e98a
--- /dev/null
+++ b/core/modules/field/modules/datetime/lib/Drupal/datetime/Type/DateTimeItem.php
@@ -0,0 +1,39 @@
+ 'date',
+ 'label' => t('Date value'),
+ );
+ }
+ return self::$propertyDefinitions;
+ }
+}
diff --git a/core/modules/forum/lib/Drupal/forum/Tests/ForumBlockTest.php b/core/modules/forum/lib/Drupal/forum/Tests/ForumBlockTest.php
index e121cb8..7c5655d 100644
--- a/core/modules/forum/lib/Drupal/forum/Tests/ForumBlockTest.php
+++ b/core/modules/forum/lib/Drupal/forum/Tests/ForumBlockTest.php
@@ -8,6 +8,7 @@
namespace Drupal\forum\Tests;
use Drupal\simpletest\WebTestBase;
+use Drupal\Core\Datetime\DrupalDateTime;
/**
* Provides automated tests for the Forum blocks.
@@ -103,16 +104,17 @@ function testActiveForumTopicsBlock() {
$topics = $this->createForumTopics(10);
// Comment on the first 5 topics.
- $timestamp = time();
+ $date = new DrupalDateTime();
$langcode = LANGUAGE_NOT_SPECIFIED;
for ($index = 0; $index < 5; $index++) {
// Get the node from the topic title.
$node = $this->drupalGetNodeByTitle($topics[$index]);
+ $date->modify('+1 minute');
$comment = entity_create('comment', array(
'nid' => $node->nid,
'subject' => $this->randomString(20),
'comment_body' => array(LANGUAGE_NOT_SPECIFIED => $this->randomString(256)),
- 'created' => $timestamp + $index,
+ 'created' => $date->getTimestamp(),
));
comment_save($comment);
}
@@ -171,20 +173,23 @@ function testActiveForumTopicsBlock() {
*/
private function createForumTopics($count = 5) {
$topics = array();
- $timestamp = time() - 24 * 60 * 60;
+ $date = new DrupalDateTime();
+ $date->modify('-24 hours');
for ($index = 0; $index < $count; $index++) {
// Generate a random subject/body.
$title = $this->randomName(20);
$body = $this->randomName(200);
+ // Forum posts are ordered by timestamp, so force a unique timestamp by
+ // changing the date.
+ $date->modify('+1 minute');
$langcode = LANGUAGE_NOT_SPECIFIED;
$edit = array(
'title' => $title,
"body[$langcode][0][value]" => $body,
- // Forum posts are ordered by timestamp, so force a unique timestamp by
- // adding the index.
- 'date' => date('c', $timestamp + $index),
+ 'date[date]' => $date->format('Y-m-d'),
+ 'date[time]' => $date->format('H:i:s'),
);
// Create the forum topic, preselecting the forum ID via a URL parameter.
diff --git a/core/modules/node/lib/Drupal/node/NodeFormController.php b/core/modules/node/lib/Drupal/node/NodeFormController.php
index 5add3df..4061fec 100644
--- a/core/modules/node/lib/Drupal/node/NodeFormController.php
+++ b/core/modules/node/lib/Drupal/node/NodeFormController.php
@@ -9,6 +9,7 @@
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityFormController;
+use Drupal\Core\Datetime\DrupalDateTime;
/**
* Form controller for the node edit forms.
@@ -39,7 +40,7 @@ protected function prepareEntity(EntityInterface $node) {
$node->created = REQUEST_TIME;
}
else {
- $node->date = format_date($node->created, 'custom', 'Y-m-d H:i:s O');
+ $node->date = new DrupalDateTime($node->created);
// Remove the log message from the original node entity.
$node->log = NULL;
}
@@ -189,12 +190,11 @@ public function form(array $form, array &$form_state, EntityInterface $node) {
'#weight' => -1,
'#description' => t('Leave blank for %anonymous.', array('%anonymous' => $user_config->get('anonymous'))),
);
-
+ $format = variable_get('date_format_html_date', 'Y-m-d') . ' ' . variable_get('date_format_html_time', 'H:i:s');
$form['author']['date'] = array(
- '#type' => 'textfield',
+ '#type' => 'datetime',
'#title' => t('Authored on'),
- '#maxlength' => 25,
- '#description' => t('Format: %time. The date format is YYYY-MM-DD and %timezone is the time zone offset from UTC. Leave blank to use the time of form submission.', array('%time' => !empty($node->date) ? date_format(date_create($node->date), 'Y-m-d H:i:s O') : format_date($node->created, 'custom', 'Y-m-d H:i:s O'), '%timezone' => !empty($node->date) ? date_format(date_create($node->date), 'O') : format_date($node->created, 'custom', 'O'))),
+ '#description' => t('Format: %format. Leave blank to use the time of form submission.', array('%format' => datetime_format_example($format))),
'#default_value' => !empty($node->date) ? $node->date : '',
);
@@ -288,7 +288,8 @@ public function validate(array $form, array &$form_state) {
}
// Validate the "authored on" field.
- if (!empty($node->date) && strtotime($node->date) === FALSE) {
+ // The date element contains the date object.
+ if ($node->date instanceOf DrupalDateTime && $node->date->hasErrors()) {
form_set_error('date', t('You have to specify a valid date.'));
}
diff --git a/core/modules/node/node.module b/core/modules/node/node.module
index 5c11424..33305f5 100644
--- a/core/modules/node/node.module
+++ b/core/modules/node/node.module
@@ -18,6 +18,7 @@
use Drupal\node\Plugin\Core\Entity\Node;
use Drupal\file\Plugin\Core\Entity\File;
use Drupal\Core\Entity\EntityInterface;
+use Drupal\Core\Datetime\DrupalDateTime;
/**
* Denotes that the node is not published.
@@ -1025,7 +1026,7 @@ function node_submit(Node $node) {
$node->revision_uid = $user->uid;
}
- $node->created = !empty($node->date) ? strtotime($node->date) : REQUEST_TIME;
+ $node->created = $node->date instanceOf DrupalDateTime ? $node->date->getTimestamp() : REQUEST_TIME;
$node->validated = TRUE;
return $node;
diff --git a/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php b/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php
index ebadf43..812e95a 100644
--- a/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php
+++ b/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php
@@ -15,6 +15,7 @@
use DOMDocument;
use DOMXPath;
use SimpleXMLElement;
+use Drupal\Core\Datetime\DrupalDateTime;
/**
* Test case for typical Drupal tests.
@@ -1186,7 +1187,6 @@ protected function drupalPost($path, $edit, $submit, array $options = array(), a
// handleForm() function, it's not currently a requirement.
$submit_matches = TRUE;
}
-
// We post only if we managed to handle every field in edit and the
// submit button matches.
if (!$edit && ($submit_matches || !isset($submit))) {
@@ -1522,6 +1522,10 @@ protected function handleForm(&$post, &$edit, &$upload, $submit, $form) {
case 'password':
case 'email':
case 'search':
+ case 'date':
+ case 'time':
+ case 'datetime':
+ case 'datetime-local';
$post[$name] = $edit[$name];
unset($edit[$name]);
break;
diff --git a/core/modules/system/lib/Drupal/system/Tests/Datetime/DateTimePlusTest.php b/core/modules/system/lib/Drupal/system/Tests/Datetime/DateTimePlusTest.php
new file mode 100644
index 0000000..9eb0162
--- /dev/null
+++ b/core/modules/system/lib/Drupal/system/Tests/Datetime/DateTimePlusTest.php
@@ -0,0 +1,418 @@
+ 'DateTimePlus',
+ 'description' => 'Test DateTimePlus functionality.',
+ 'group' => 'Datetime',
+ );
+ }
+
+ /**
+ * Set up required modules.
+ */
+ public static $modules = array();
+
+ /**
+ * Test creating dates from string input.
+ */
+ public function testDateStrings() {
+
+ // Create date object from datetime string.
+ $input = '2009-03-07 10:30';
+ $timezone = 'America/Chicago';
+ $date = new DateTimePlus($input, $timezone);
+ $value = $date->format('c');
+ $expected = '2009-03-07T10:30:00-06:00';
+ $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone): should be $expected, found $value.");
+
+ // Same during daylight savings time.
+ $input = '2009-06-07 10:30';
+ $timezone = 'America/Chicago';
+ $date = new DateTimePlus($input, $timezone);
+ $value = $date->format('c');
+ $expected = '2009-06-07T10:30:00-05:00';
+ $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone): should be $expected, found $value.");
+
+ // Create date object from date string.
+ $input = '2009-03-07';
+ $timezone = 'America/Chicago';
+ $date = new DateTimePlus($input, $timezone);
+ $value = $date->format('c');
+ $expected = '2009-03-07T00:00:00-06:00';
+ $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone): should be $expected, found $value.");
+
+ // Same during daylight savings time.
+ $input = '2009-06-07';
+ $timezone = 'America/Chicago';
+ $date = new DateTimePlus($input, $timezone);
+ $value = $date->format('c');
+ $expected = '2009-06-07T00:00:00-05:00';
+ $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone): should be $expected, found $value.");
+
+ // Create date object from date string.
+ $input = '2009-03-07 10:30';
+ $timezone = 'Australia/Canberra';
+ $date = new DateTimePlus($input, $timezone);
+ $value = $date->format('c');
+ $expected = '2009-03-07T10:30:00+11:00';
+ $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone): should be $expected, found $value.");
+
+ // Same during daylight savings time.
+ $input = '2009-06-07 10:30';
+ $timezone = 'Australia/Canberra';
+ $date = new DateTimePlus($input, $timezone);
+ $value = $date->format('c');
+ $expected = '2009-06-07T10:30:00+10:00';
+ $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone): should be $expected, found $value.");
+
+ }
+
+ /**
+ * Test creating dates from arrays of date parts.
+ */
+ function testDateArrays() {
+
+ // Create date object from date array, date only.
+ $input = array('year' => 2010, 'month' => 2, 'day' => 28);
+ $timezone = 'America/Chicago';
+ $date = new DateTimePlus($input, $timezone);
+ $value = $date->format('c');
+ $expected = '2010-02-28T00:00:00-06:00';
+ $this->assertEqual($expected, $value, "Test new DateTimePlus(array('year' => 2010, 'month' => 2, 'day' => 28), $timezone): should be $expected, found $value.");
+
+ // Create date object from date array with hour.
+ $input = array('year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 10);
+ $timezone = 'America/Chicago';
+ $date = new DateTimePlus($input, $timezone);
+ $value = $date->format('c');
+ $expected = '2010-02-28T10:00:00-06:00';
+ $this->assertEqual($expected, $value, "Test new DateTimePlus(array('year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 10), $timezone): should be $expected, found $value.");
+
+ // Create date object from date array, date only.
+ $input = array('year' => 2010, 'month' => 2, 'day' => 28);
+ $timezone = 'Europe/Berlin';
+ $date = new DateTimePlus($input, $timezone);
+ $value = $date->format('c');
+ $expected = '2010-02-28T00:00:00+01:00';
+ $this->assertEqual($expected, $value, "Test new DateTimePlus(array('year' => 2010, 'month' => 2, 'day' => 28), $timezone): should be $expected, found $value.");
+
+ // Create date object from date array with hour.
+ $input = array('year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 10);
+ $timezone = 'Europe/Berlin';
+ $date = new DateTimePlus($input, $timezone);
+ $value = $date->format('c');
+ $expected = '2010-02-28T10:00:00+01:00';
+ $this->assertEqual($expected, $value, "Test new DateTimePlus(array('year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 10), $timezone): should be $expected, found $value.");
+
+ }
+
+ /**
+ * Test creating dates from timestamps.
+ */
+ function testDateTimestamp() {
+
+ // Create date object from a unix timestamp and display it in
+ // local time.
+ $input = 0;
+ $timezone = 'UTC';
+ $date = new DateTimePlus($input, $timezone);
+ $value = $date->format('c');
+ $expected = '1970-01-01T00:00:00+00:00';
+ $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone): should be $expected, found $value.");
+
+ $expected = 'UTC';
+ $value = $date->getTimeZone()->getName();
+ $this->assertEqual($expected, $value, "The current timezone is $value: should be $expected.");
+ $expected = 0;
+ $value = $date->getOffset();
+ $this->assertEqual($expected, $value, "The current offset is $value: should be $expected.");
+
+ $timezone = 'America/Los_Angeles';
+ $date->setTimezone(new DateTimeZone($timezone));
+ $value = $date->format('c');
+ $expected = '1969-12-31T16:00:00-08:00';
+ $this->assertEqual($expected, $value, "Test \$date->setTimezone(new DateTimeZone($timezone)): should be $expected, found $value.");
+
+ $expected = 'America/Los_Angeles';
+ $value = $date->getTimeZone()->getName();
+ $this->assertEqual($expected, $value, "The current timezone should be $expected, found $value.");
+ $expected = '-28800';
+ $value = $date->getOffset();
+ $this->assertEqual($expected, $value, "The current offset should be $expected, found $value.");
+
+ // Create a date using the timestamp of zero, then display its
+ // value both in UTC and the local timezone.
+ $input = 0;
+ $timezone = 'America/Los_Angeles';
+ $date = new DateTimePlus($input, $timezone);
+ $offset = $date->getOffset();
+ $value = $date->format('c');
+ $expected = '1969-12-31T16:00:00-08:00';
+ $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone): should be $expected, found $value.");
+
+ $expected = 'America/Los_Angeles';
+ $value = $date->getTimeZone()->getName();
+ $this->assertEqual($expected, $value, "The current timezone should be $expected, found $value.");
+ $expected = '-28800';
+ $value = $date->getOffset();
+ $this->assertEqual($expected, $value, "The current offset should be $expected, found $value.");
+
+ $timezone = 'UTC';
+ $date->setTimezone(new DateTimeZone($timezone));
+ $value = $date->format('c');
+ $expected = '1970-01-01T00:00:00+00:00';
+ $this->assertEqual($expected, $value, "Test \$date->setTimezone(new DateTimeZone($timezone)): should be $expected, found $value.");
+
+ $expected = 'UTC';
+ $value = $date->getTimeZone()->getName();
+ $this->assertEqual($expected, $value, "The current timezone should be $expected, found $value.");
+ $expected = '0';
+ $value = $date->getOffset();
+ $this->assertEqual($expected, $value, "The current offset should be $expected, found $value.");
+ }
+
+ /**
+ * Test timezone manipulation.
+ */
+ function testTimezoneConversion() {
+
+ // Create date object from datetime string in UTC, and convert
+ // it to a local date.
+ $input = '1970-01-01 00:00:00';
+ $timezone = 'UTC';
+ $date = new DateTimePlus($input, $timezone);
+ $value = $date->format('c');
+ $expected = '1970-01-01T00:00:00+00:00';
+ $this->assertEqual($expected, $value, "Test new DateTimePlus('$input', '$timezone'): should be $expected, found $value.");
+
+ $expected = 'UTC';
+ $value = $date->getTimeZone()->getName();
+ $this->assertEqual($expected, $value, "The current timezone is $value: should be $expected.");
+ $expected = 0;
+ $value = $date->getOffset();
+ $this->assertEqual($expected, $value, "The current offset is $value: should be $expected.");
+
+ $timezone = 'America/Los_Angeles';
+ $date->setTimezone(new DateTimeZone($timezone));
+ $value = $date->format('c');
+ $expected = '1969-12-31T16:00:00-08:00';
+ $this->assertEqual($expected, $value, "Test \$date->setTimezone(new DateTimeZone($timezone)): should be $expected, found $value.");
+
+ $expected = 'America/Los_Angeles';
+ $value = $date->getTimeZone()->getName();
+ $this->assertEqual($expected, $value, "The current timezone should be $expected, found $value.");
+ $expected = '-28800';
+ $value = $date->getOffset();
+ $this->assertEqual($expected, $value, "The current offset should be $expected, found $value.");
+
+ // Convert the local time to UTC using string input.
+ $input = '1969-12-31 16:00:00';
+ $timezone = 'America/Los_Angeles';
+ $date = new DateTimePlus($input, $timezone);
+ $offset = $date->getOffset();
+ $value = $date->format('c');
+ $expected = '1969-12-31T16:00:00-08:00';
+ $this->assertEqual($expected, $value, "Test new DateTimePlus('$input', '$timezone'): should be $expected, found $value.");
+
+ $expected = 'America/Los_Angeles';
+ $value = $date->getTimeZone()->getName();
+ $this->assertEqual($expected, $value, "The current timezone should be $expected, found $value.");
+ $expected = '-28800';
+ $value = $date->getOffset();
+ $this->assertEqual($expected, $value, "The current offset should be $expected, found $value.");
+
+ $timezone = 'UTC';
+ $date->setTimezone(new DateTimeZone($timezone));
+ $value = $date->format('c');
+ $expected = '1970-01-01T00:00:00+00:00';
+ $this->assertEqual($expected, $value, "Test \$date->setTimezone(new DateTimeZone($timezone)): should be $expected, found $value.");
+
+ $expected = 'UTC';
+ $value = $date->getTimeZone()->getName();
+ $this->assertEqual($expected, $value, "The current timezone should be $expected, found $value.");
+ $expected = '0';
+ $value = $date->getOffset();
+ $this->assertEqual($expected, $value, "The current offset should be $expected, found $value.");
+
+ // Convert the local time to UTC using string input.
+ $input = '1969-12-31 16:00:00';
+ $timezone = 'Europe/Warsaw';
+ $date = new DateTimePlus($input, $timezone);
+ $offset = $date->getOffset();
+ $value = $date->format('c');
+ $expected = '1969-12-31T16:00:00+01:00';
+ $this->assertEqual($expected, $value, "Test new DateTimePlus('$input', '$timezone'): should be $expected, found $value.");
+
+ $expected = 'Europe/Warsaw';
+ $value = $date->getTimeZone()->getName();
+ $this->assertEqual($expected, $value, "The current timezone should be $expected, found $value.");
+ $expected = '+3600';
+ $value = $date->getOffset();
+ $this->assertEqual($expected, $value, "The current offset should be $expected, found $value.");
+
+ }
+
+ /**
+ * Test creating dates from format strings.
+ */
+ function testDateFormat() {
+
+ // Create a year-only date.
+ $input = '2009';
+ $timezone = NULL;
+ $format = 'Y';
+ $date = new DateTimePlus($input, $timezone, $format);
+ $value = $date->format('Y');
+ $expected = '2009';
+ $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone, $format): should be $expected, found $value.");
+
+ // Create a month and year-only date.
+ $input = '2009-10';
+ $timezone = NULL;
+ $format = 'Y-m';
+ $date = new DateTimePlus($input, $timezone, $format);
+ $value = $date->format('Y-m');
+ $expected = '2009-10';
+ $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone, $format): should be $expected, found $value.");
+
+ // Create a time-only date.
+ $input = 'T10:30:00';
+ $timezone = NULL;
+ $format = '\TH:i:s';
+ $date = new DateTimePlus($input, $timezone, $format);
+ $value = $date->format('H:i:s');
+ $expected = '10:30:00';
+ $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone, $format): should be $expected, found $value.");
+
+ // Create a time-only date.
+ $input = '10:30:00';
+ $timezone = NULL;
+ $format = 'H:i:s';
+ $date = new DateTimePlus($input, $timezone, $format);
+ $value = $date->format('H:i:s');
+ $expected = '10:30:00';
+ $this->assertEqual($expected, $value, "Test new DateTimePlus($input, $timezone, $format): should be $expected, found $value.");
+
+ }
+
+ /**
+ * Test invalid date handling.
+ */
+ function testInvalidDates() {
+
+ // Test for invalid month names when we are using a short version
+ // of the month.
+ $input = '23 abc 2012';
+ $timezone = NULL;
+ $format = 'd M Y';
+ $date = new DateTimePlus($input, $timezone, $format);
+ $this->assertNotEqual(count($date->getErrors()), 0, "$input contains an invalid month name and produces errors.");
+
+ // Test for invalid hour.
+ $input = '0000-00-00T45:30:00';
+ $timezone = NULL;
+ $format = 'Y-m-d\TH:i:s';
+ $date = new DateTimePlus($input, $timezone, $format);
+ $this->assertNotEqual(count($date->getErrors()), 0, "$input contains an invalid hour and produces errors.");
+
+ // Test for invalid day.
+ $input = '0000-00-99T05:30:00';
+ $timezone = NULL;
+ $format = 'Y-m-d\TH:i:s';
+ $date = new DateTimePlus($input, $timezone, $format);
+ $this->assertNotEqual(count($date->getErrors()), 0, "$input contains an invalid day and produces errors.");
+
+ // Test for invalid month.
+ $input = '0000-75-00T15:30:00';
+ $timezone = NULL;
+ $format = 'Y-m-d\TH:i:s';
+ $date = new DateTimePlus($input, $timezone, $format);
+ $this->assertNotEqual(count($date->getErrors()), 0, "$input contains an invalid month and produces errors.");
+
+ // Test for invalid year.
+ $input = '11-08-01T15:30:00';
+ $timezone = NULL;
+ $format = 'Y-m-d\TH:i:s';
+ $date = new DateTimePlus($input, $timezone, $format);
+ $this->assertNotEqual(count($date->getErrors()), 0, "$input contains an invalid year and produces errors.");
+
+ // Test for invalid year from date array. 10000 as a year will
+ // create an exception error in the PHP DateTime object.
+ $input = array('year' => 10000, 'month' => 7, 'day' => 8, 'hour' => 8, 'minute' => 0, 'second' => 0);
+ $timezone = 'America/Chicago';
+ $date = new DateTimePlus($input, $timezone);
+ $this->assertNotEqual(count($date->getErrors()), 0, "array('year' => 10000, 'month' => 7, 'day' => 8, 'hour' => 8, 'minute' => 0, 'second' => 0) contains an invalid year and produces errors.");
+
+ // Test for invalid month from date array.
+ $input = array('year' => 2010, 'month' => 27, 'day' => 8, 'hour' => 8, 'minute' => 0, 'second' => 0);
+ $timezone = 'America/Chicago';
+ $date = new DateTimePlus($input, $timezone);
+ $this->assertNotEqual(count($date->getErrors()), 0, "array('year' => 2010, 'month' => 27, 'day' => 8, 'hour' => 8, 'minute' => 0, 'second' => 0) contains an invalid month and produces errors.");
+
+ // Test for invalid hour from date array.
+ $input = array('year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 80, 'minute' => 0, 'second' => 0);
+ $timezone = 'America/Chicago';
+ $date = new DateTimePlus($input, $timezone);
+ $this->assertNotEqual(count($date->getErrors()), 0, "array('year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 80, 'minute' => 0, 'second' => 0) contains an invalid hour and produces errors.");
+
+ // Test for invalid minute from date array.
+ $input = array('year' => 2010, 'month' => 7, 'day' => 8, 'hour' => 8, 'minute' => 88, 'second' => 0);
+ $timezone = 'America/Chicago';
+ $date = new DateTimePlus($input, $timezone);
+ $this->assertNotEqual(count($date->getErrors()), 0, "array('year' => 2010, 'month' => 7, 'day' => 8, 'hour' => 8, 'minute' => 88, 'second' => 0) contains an invalid minute and produces errors.");
+
+ }
+
+ /**
+ * Test that DrupalDateTime can detect the right timezone to use.
+ * When specified or not.
+ */
+ public function testDateTimezone() {
+ global $user;
+
+ $date_string = '2007-01-31 21:00:00';
+
+ // 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 DateTimePlus($date_string);
+ $timezone = $date->getTimezone()->getName();
+ $this->assertTrue($timezone == $system_timezone, 'DateTimePlus uses the system timezone when there is no site timezone.');
+
+ // Create a date object with a specified timezone name.
+ $date = new DateTimePlus($date_string, 'America/Yellowknife');
+ $timezone = $date->getTimezone()->getName();
+ $this->assertTrue($timezone == 'America/Yellowknife', 'DateTimePlus uses the specified timezone if provided.');
+
+ // Create a date object with a timezone object.
+ $date = new DateTimePlus($date_string, new \DateTimeZone('Australia/Canberra'));
+ $timezone = $date->getTimezone()->getName();
+ $this->assertTrue($timezone == 'Australia/Canberra', 'DateTimePlus uses the specified timezone if provided.');
+
+ // Create a date object with another date object.
+ $new_date = new DateTimePlus('now', 'Pacific/Midway');
+ $date = new DateTimePlus($new_date);
+ $timezone = $date->getTimezone()->getName();
+ $this->assertTrue($timezone == 'Pacific/Midway', 'DateTimePlus uses the specified timezone if provided.');
+
+ }
+}
diff --git a/core/modules/system/lib/Drupal/system/Tests/Datetime/DrupalDateTimeTest.php b/core/modules/system/lib/Drupal/system/Tests/Datetime/DrupalDateTimeTest.php
new file mode 100644
index 0000000..ea10896
--- /dev/null
+++ b/core/modules/system/lib/Drupal/system/Tests/Datetime/DrupalDateTimeTest.php
@@ -0,0 +1,110 @@
+ 'DrupalDateTime',
+ 'description' => 'Test DrupalDateTime functionality.',
+ 'group' => 'Datetime',
+ );
+ }
+
+ /**
+ * Set up required modules.
+ */
+ public static $modules = array();
+
+ /**
+ * Test setup.
+ */
+ public function setUp() {
+ parent::setUp();
+
+ }
+
+ /**
+ * 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.
+ variable_set('date_default_timezone', NULL);
+ variable_set('configurable_timezones', 0);
+
+ // 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.
+ variable_set('date_default_timezone', 'Europe/Warsaw');
+
+ // 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.
+ variable_set('configurable_timezones', 1);
+ $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->mail, 'timezone' => 'Asia/Manila');
+ $this->drupalPost('user/' . $test_user->uid . '/edit', $edit, t('Save'));
+
+ // Disable session saving as we are about to modify the global $user.
+ drupal_save_session(FALSE);
+ // Save the original user and then replace it with the test user.
+ $real_user = $user;
+ $user = user_load($test_user->uid, 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_save_session(TRUE);
+
+
+ }
+}
diff --git a/core/modules/system/lib/Drupal/system/Tests/Form/FormTest.php b/core/modules/system/lib/Drupal/system/Tests/Form/FormTest.php
index 15d12d8..6d1f477 100644
--- a/core/modules/system/lib/Drupal/system/Tests/Form/FormTest.php
+++ b/core/modules/system/lib/Drupal/system/Tests/Form/FormTest.php
@@ -510,7 +510,7 @@ function testDisabledElements() {
// All the elements should be marked as disabled, including the ones below
// the disabled container.
- $this->assertEqual(count($disabled_elements), 40, 'The correct elements have the disabled property in the HTML code.');
+ $this->assertEqual(count($disabled_elements), 39, 'The correct elements have the disabled property in the HTML code.');
$this->drupalPost(NULL, $edit, t('Submit'));
$returned_values['hijacked'] = drupal_json_decode($this->content);
@@ -560,7 +560,7 @@ function testDisabledMarkup() {
'textarea' => 'textarea',
'select' => 'select',
'weight' => 'select',
- 'date' => 'select',
+ 'datetime' => 'datetime',
);
foreach ($form as $name => $item) {
diff --git a/core/modules/system/lib/Drupal/system/Tests/TypedData/TypedDataTest.php b/core/modules/system/lib/Drupal/system/Tests/TypedData/TypedDataTest.php
index 62bd35e..66a4272 100644
--- a/core/modules/system/lib/Drupal/system/Tests/TypedData/TypedDataTest.php
+++ b/core/modules/system/lib/Drupal/system/Tests/TypedData/TypedDataTest.php
@@ -8,7 +8,7 @@
namespace Drupal\system\Tests\TypedData;
use Drupal\simpletest\WebTestBase;
-use DateTime;
+use Drupal\Core\Datetime\DrupalDateTime;
use DateInterval;
/**
@@ -72,7 +72,7 @@ public function testGetAndSet() {
$this->assertNull($wrapper->getValue(), 'Float wrapper is null-able.');
// Date type.
- $value = new DateTime('@' . REQUEST_TIME);
+ $value = new DrupalDateTime();
$wrapper = $this->createTypedData(array('type' => 'date'), $value);
$this->assertTrue($wrapper->getValue() === $value, 'Date value was fetched.');
$new_value = REQUEST_TIME + 1;
diff --git a/core/modules/system/system.module b/core/modules/system/system.module
index 4475104..6e8fd68 100644
--- a/core/modules/system/system.module
+++ b/core/modules/system/system.module
@@ -480,11 +480,25 @@ function system_element_info() {
);
$types['date'] = array(
'#input' => TRUE,
- '#element_validate' => array('date_validate'),
- '#process' => array('form_process_date'),
'#theme' => 'date',
'#theme_wrappers' => array('form_element'),
);
+ $types['datetime'] = array(
+ '#input' => TRUE,
+ '#element_validate' => array('datetime_validate'),
+ '#process' => array('form_process_datetime'),
+ '#theme' => 'form_datetime',
+ '#theme_wrappers' => array('form_element'),
+ '#date_date_format' => variable_get('date_format_html_date', 'Y-m-d'),
+ '#date_date_element' => 'date',
+ '#date_date_callbacks' => array('datetime_jquery_datepicker_callback'),
+ '#date_time_format' => variable_get('date_format_html_time', 'H:i:s'),
+ '#date_time_element' => 'time',
+ '#date_time_callbacks' => array(),
+ '#date_year_range' => '1900:2050',
+ '#date_increment' => 1,
+ '#date_timezone' => '',
+ );
$types['file'] = array(
'#input' => TRUE,
'#size' => 60,
@@ -1954,7 +1968,21 @@ function system_library_info() {
array('system', 'drupalSettings'),
),
);
-
+ $libraries['drupal.datepicker'] = array(
+ 'title' => 'Drupal datepicker',
+ 'version' => VERSION,
+ 'js' => array(
+ 'core/misc/datepicker.js' => array(),
+ ),
+ 'dependencies' => array(
+ array('system', 'jquery'),
+ array('system', 'jquery.ui.core'),
+ array('system', 'jquery.ui.datepicker'),
+ array('system', 'jquery.once'),
+ array('system', 'drupal'),
+ array('system', 'drupalSettings'),
+ ),
+ );
$libraries['drupal.system'] = array(
'title' => 'System',
'version' => VERSION,
diff --git a/core/modules/system/tests/modules/form_test/form_test.module b/core/modules/system/tests/modules/form_test/form_test.module
index 03b7cb8..4f4676d 100644
--- a/core/modules/system/tests/modules/form_test/form_test.module
+++ b/core/modules/system/tests/modules/form_test/form_test.module
@@ -6,6 +6,7 @@
*/
use Drupal\form_test\Callbacks;
+use Drupal\Core\Datetime\DrupalDateTime;
/**
* Implements hook_menu().
@@ -1721,23 +1722,6 @@ function _form_test_disabled_elements($form, &$form_state) {
'#disabled' => TRUE,
);
- // Date.
- $form['date'] = array(
- '#type' => 'date',
- '#title' => 'date',
- '#disabled' => TRUE,
- '#default_value' => array(
- 'day' => 19,
- 'month' => 11,
- 'year' => 1978,
- ),
- '#test_hijack_value' => array(
- 'day' => 20,
- 'month' => 12,
- 'year' => 1979,
- ),
- );
-
// The #disabled state should propagate to children.
$form['disabled_container'] = array(
'#disabled' => TRUE,
@@ -1751,6 +1735,19 @@ function _form_test_disabled_elements($form, &$form_state) {
);
}
+ // Date.
+ $date = new DrupalDateTime('1978-11-01 10:30:00', 'Europe/Berlin');
+ $expected = array('date' => '1978-11-01 10:30:00', 'timezone_type' => 3, 'timezone' => 'Europe/Berlin',);
+ $form['disabled_container']['disabled_container_datetime'] = array(
+ '#type' => 'datetime',
+ '#title' => 'datetime',
+ '#default_value' => $date,
+ '#expected_value' => $expected,
+ '#test_hijack_value' => new DrupalDateTime('1978-12-02 11:30:00', 'Europe/Berlin'),
+ '#date_timezone' => 'Europe/Berlin',
+ );
+
+
// Try to hijack the email field with a valid email.
$form['disabled_container']['disabled_container_email'] = array(
'#type' => 'email',
diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/LegacyTest.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/LegacyTest.php
index d00f373..d4f7be5 100644
--- a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/LegacyTest.php
+++ b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/LegacyTest.php
@@ -7,6 +7,8 @@
namespace Drupal\taxonomy\Tests;
+use Drupal\Core\Datetime\DrupalDateTime;
+
/**
* Test for legacy node bug.
*/
@@ -34,14 +36,16 @@ function setUp() {
function testTaxonomyLegacyNode() {
// Posts an article with a taxonomy term and a date prior to 1970.
$langcode = LANGUAGE_NOT_SPECIFIED;
+ $date = new DrupalDateTime('1969-01-01 00:00:00');
$edit = array();
$edit['title'] = $this->randomName();
- $edit['date'] = '1969-01-01 00:00:00 -0500';
+ $edit['date[date]'] = $date->format('Y-m-d');
+ $edit['date[time]'] = $date->format('H:i:s');
$edit["body[$langcode][0][value]"] = $this->randomName();
$edit["field_tags[$langcode]"] = $this->randomName();
$this->drupalPost('node/add/article', $edit, t('Save'));
// Checks that the node has been saved.
$node = $this->drupalGetNodeByTitle($edit['title']);
- $this->assertEqual($node->created, strtotime($edit['date']), 'Legacy node was saved with the right date.');
+ $this->assertEqual($node->created, $date->getTimestamp(), 'Legacy node was saved with the right date.');
}
}