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.
Comments
Comment #2
codersukanta CreditAttribution: codersukanta at Srijan | A Material+ Company for Drupal India Association commentedI was trying to demonstrate the issue, Here are my findings.
Default value is working as expected, default value is set to 07-10-2020 as I am testing it on 23-09-2020, Which is right behaviour.
But I can see that the module https://www.drupal.org/project/datetime_testing is not available for drupal 9.
I just wanted to confirm that how did you use datetime_testing module for drupal 9.
Comment #9
FrontmobeThis 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 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.