Relative dates for fields are not calculated with respect to Drupal::time()

Created on 17 September 2020, over 4 years ago
Updated 21 July 2023, over 1 year ago

Problem/Motivation

Relative dates set in the Field UI are calculated based on the current time, not Drupal::time().

Steps to reproduce

1. Add a date field to a node.
2. For the date field's default date, select "relative date" of "+2 weeks".
3. Use the https://www.drupal.org/project/datetime_testing module to lock the time (e.g., drush datetime:set 2020-07-07 00:00:00.
4. Create a node. The date for the date field will be +2 weeks from the current time, not from the time that Drupal::time() is set to (2020-07-07).

Expected result:
2020-07-21

Actual result:
2020-10-01 (when tested on 2020-09-17)

When using hook_node_presave(), code like the following will give the correct value based on Drupal::time().

    $drupal_current_timestamp = \Drupal::time()->getCurrentTime();
    // Seconds x minutes x hours x days
    $two_weeks_seconds = 60 * 60 * 24 * 14;
    $twoweekslater_timestamp = $drupal_current_timestamp + $two_weeks_seconds;
    $user->set('field_datetime', MYMODULE_get_formatted_date_from_timestamp("$twoweekslater_timestamp"));

Proposed resolution

Calculate relative dates based on Drupal::time() to enable better testing.

Remaining tasks

User interface changes

API changes

Data model changes

Release notes snippet

πŸ“Œ Task
Status

Active

Version

11.0 πŸ”₯

Component
DatetimeΒ  β†’

Last updated 3 days ago

Created by

πŸ‡―πŸ‡΅Japan ptmkenny

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • πŸ‡³πŸ‡±Netherlands frontmobe Amsterdam

    This behaviour still exists in the Drupal 10.1 / 11.x branches.

    Since the the issue does not break anything but instead deals with doing testing the right way, I am changing the category from "Bug report" to "Task" here.

    Looking for another issue where this might be addressed, resulted only in the much broader meta issue πŸ“Œ [meta][no patch] Replace uses of REQUEST_TIME and time() with time service Active calling for uses of time() and REQUEST_TIME to be replaced by the time service, like in this issue.

    Using the time service here does seem useful because consistent use has clear benefits, as outlined here β†’ .

Production build 0.71.5 2024