formatTimeDiffSince example

$this->displayOptions['type'] = 'datetime_time_ago';
      $this->displayOptions['settings'] = [
        'future_format' => '@interval in the future',
        'past_format' => '@interval in the past',
        'granularity' => 3,
      ];
      $display_repository->getViewDisplay($this->field->getTargetEntityTypeId()$this->field->getTargetBundle(), 'full')
        ->setComponent($field_name$this->displayOptions)
        ->save();
      $expected = new FormattableMarkup($this->displayOptions['settings']['past_format'][
        '@interval' => $this->dateFormatter->formatTimeDiffSince($timestamp['granularity' => $this->displayOptions['settings']['granularity']]),
      ]);
      $output = $this->renderTestEntity($id);
      $this->assertStringContainsString((string) $expected$outputnew FormattableMarkup('Formatted date field using datetime_time_ago format displayed as %expected in %timezone.', [
        '%expected' => $expected,
        '%timezone' => $timezone,
      ]));

      // Verify that the 'datetime_time_ago' formatter works for intervals in the       // future. First update the test entity so that the date difference always       // has the same interval. Since the database always stores UTC, and the       // interval will use this, force the test date to use UTC and not the local
$tests['[node:title]'] = Html::escape($node->getTitle());
    $tests['[node:body]'] = $node->body->processed;
    $tests['[node:summary]'] = $node->body->summary_processed;
    $tests['[node:langcode]'] = $node->language()->getId();
    $tests['[node:url]'] = $node->toUrl('canonical', $url_options)->toString();
    $tests['[node:edit-url]'] = $node->toUrl('edit-form', $url_options)->toString();
    $tests['[node:author]'] = $account->getAccountName();
    $tests['[node:author:uid]'] = $node->getOwnerId();
    $tests['[node:author:name]'] = $account->getAccountName();
    /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
    $date_formatter = $this->container->get('date.formatter');
    $tests['[node:created:since]'] = $date_formatter->formatTimeDiffSince($node->getCreatedTime()['langcode' => $this->interfaceLanguage->getId()]);
    $tests['[node:changed:since]'] = $date_formatter->formatTimeDiffSince($node->getChangedTime()['langcode' => $this->interfaceLanguage->getId()]);

    $base_bubbleable_metadata = BubbleableMetadata::createFromObject($node);

    $metadata_tests = [];
    $metadata_tests['[node:nid]'] = $base_bubbleable_metadata;
    $metadata_tests['[node:vid]'] = $base_bubbleable_metadata;
    $metadata_tests['[node:type]'] = $base_bubbleable_metadata;
    $metadata_tests['[node:type-name]'] = $base_bubbleable_metadata;
    $metadata_tests['[node:title]'] = $base_bubbleable_metadata;
    $metadata_tests['[node:body]'] = $base_bubbleable_metadata;
    

    }

    $this->assertEmpty(array_keys(array_diff_key($result_accounts$accounts)), 'Ensure all accounts are listed.');
    foreach ($result_accounts as $name => $values) {
      $this->assertEquals($accounts[$name]->status->value, $values['status'] == 'active');
    }

    $expected_roles = ['custom_role_1', 'custom_role_2'];
    $this->assertEquals($expected_roles$result_accounts[$role_account_name]['roles'], 'Ensure roles are listed properly.');

    $this->assertEquals(\Drupal::service('date.formatter')->formatTimeDiffSince($accounts[$timestamp_user]->created->value)$result_accounts[$timestamp_user]['member_for'], 'Ensure the right member time is displayed.');

    $this->assertEquals('never', $result_accounts[$timestamp_user]['last_access'], 'Ensure the last access time is "never".');
  }

}
$tests['[comment:cid]'] = $comment->id();
    $tests['[comment:hostname]'] = $comment->getHostname();
    $tests['[comment:author]'] = Html::escape($comment->getAuthorName());
    $tests['[comment:mail]'] = $this->adminUser->getEmail();
    $tests['[comment:homepage]'] = UrlHelper::filterBadProtocol($comment->getHomepage());
    $tests['[comment:title]'] = Html::escape($comment->getSubject());
    $tests['[comment:body]'] = $comment->comment_body->processed;
    $tests['[comment:langcode]'] = $comment->language()->getId();
    $tests['[comment:url]'] = $comment->toUrl('canonical', $url_options + ['fragment' => 'comment-' . $comment->id()])->toString();
    $tests['[comment:edit-url]'] = $comment->toUrl('edit-form', $url_options)->toString();
    $tests['[comment:created]'] = \Drupal::service('date.formatter')->format($comment->getCreatedTime(), 'medium', ['langcode' => $language_interface->getId()]);
    $tests['[comment:created:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getCreatedTime()['langcode' => $language_interface->getId()]);
    $tests['[comment:changed:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getChangedTimeAcrossTranslations()['langcode' => $language_interface->getId()]);
    $tests['[comment:parent:cid]'] = $comment->hasParentComment() ? $comment->getParentComment()->id() : NULL;
    $tests['[comment:parent:title]'] = $parent_comment->getSubject();
    $tests['[comment:entity]'] = Html::escape($node->getTitle());
    // Test node specific tokens.     $tests['[comment:entity:nid]'] = $comment->getCommentedEntityId();
    $tests['[comment:entity:title]'] = Html::escape($node->getTitle());
    $tests['[comment:author:uid]'] = $comment->getOwnerId();
    $tests['[comment:author:name]'] = Html::escape($this->adminUser->getDisplayName());

    $base_bubbleable_metadata = BubbleableMetadata::createFromObject($comment);
    

  if (version_compare(phpversion(), \Drupal::MINIMUM_PHP) < 0) {
    $requirements['php']['description'] = t('Your PHP installation is too old. Drupal requires at least PHP %version.', ['%version' => \Drupal::MINIMUM_PHP]);
    $requirements['php']['severity'] = REQUIREMENT_ERROR;
  }

  // Report cron status   if ($phase == 'runtime') {
    $cron_last = \Drupal::state()->get('system.cron_last');

    if (is_numeric($cron_last)) {
      $requirements['cron']['value'] = t('Last run @time ago', ['@time' => \Drupal::service('date.formatter')->formatTimeDiffSince($cron_last)]);
    }
    else {
      $requirements['cron'] = [
        'description' => t('Cron has not run. It appears cron jobs have not been setup on your system. Check the help pages for <a href=":url">configuring cron jobs</a>.', [':url' => 'https://www.drupal.org/docs/administering-a-drupal-site/cron-automated-tasks/cron-automated-tasks-overview']),
        'severity' => REQUIREMENT_ERROR,
        'value' => t('Never run'),
      ];
    }

    $requirements['cron']['description'] .= ' ' . t('You can <a href=":cron">run cron manually</a>.', [':cron' => Url::fromRoute('system.run_cron')->toString()]);

    
'html_datetime' => $date_formatter->format($time, 'html_datetime', '', $timezone),
        'html_month' => $date_formatter->format($time, 'html_month', '', $timezone),
        'html_time' => $date_formatter->format($time, 'html_time', '', $timezone),
        'html_week' => $date_formatter->format($time, 'html_week', '', $timezone),
        'html_year' => $date_formatter->format($time, 'html_year', '', $timezone),
        'html_yearless_date' => $date_formatter->format($time, 'html_yearless_date', '', $timezone),
      ];
      $this->assertRenderedDatesEqual($view$dates$timezone);
    }

    // Check times in the past.     $time_since = $date_formatter->formatTimeDiffSince($time);
    $intervals = [
      'raw time ago' => $time_since,
      'time ago' => "$time_since ago",
      'raw time span' => $time_since,
      'inverse time span' => "-$time_since",
      'time span' => "$time_since ago",
    ];
    $this->assertRenderedDatesEqual($view$intervals);

    // Check times in the future.     $time = gmmktime(0, 0, 0, 1, 1, 2050);
    

    }

    foreach ($data as $settings) {
      $future_format = $settings['future_format'];
      $past_format = $settings['past_format'];
      $granularity = $settings['granularity'];
      $request_time = \Drupal::requestStack()->getCurrentRequest()->server->get('REQUEST_TIME');

      // Test a timestamp in the past       $value = $request_time - 87654321;
      $expected = new FormattableMarkup($past_format['@interval' => \Drupal::service('date.formatter')->formatTimeDiffSince($value['granularity' => $granularity])]);

      $component = $this->display->getComponent($this->fieldName);
      $component['type'] = 'timestamp_ago';
      $component['settings'] = $settings;
      $this->display->setComponent($this->fieldName, $component);

      $entity = EntityTest::create([]);
      $entity->{$this->fieldName}->value = $value;

      $this->renderEntityFields($entity$this->display);
      $this->assertRaw($expected);

      
$summary = parent::settingsSummary();

    $future_date = new DrupalDateTime('1 year 1 month 1 week 1 day 1 hour 1 minute');
    $past_date = new DrupalDateTime('-1 year -1 month -1 week -1 day -1 hour -1 minute');
    $granularity = $this->getSetting('granularity');
    $options = [
      'granularity' => $granularity,
      'return_as_object' => FALSE,
    ];

    $future_date_interval = new FormattableMarkup($this->getSetting('future_format')['@interval' => $this->dateFormatter->formatTimeDiffUntil($future_date->getTimestamp()$options)]);
    $past_date_interval = new FormattableMarkup($this->getSetting('past_format')['@interval' => $this->dateFormatter->formatTimeDiffSince($past_date->getTimestamp()$options)]);

    $summary[] = $this->t('Future date: %display', ['%display' => $future_date_interval]);
    $summary[] = $this->t('Past date: %display', ['%display' => $past_date_interval]);

    return $summary;
  }

  /** * {@inheritdoc} */
  public function viewElements(FieldItemListInterface $items$langcode) {
    
if (in_array($format['custom', 'raw time ago', 'time ago', 'raw time hence', 'time hence', 'raw time span', 'time span', 'raw time span', 'inverse time span', 'time span'])) {
      $custom_format = $this->options['custom_date_format'];
    }

    if ($value) {
      $timezone = !empty($this->options['timezone']) ? $this->options['timezone'] : NULL;
      // Will be positive for a datetime in the past (ago), and negative for a       // datetime in the future (hence).       $time_diff = REQUEST_TIME - $value;
      switch ($format) {
        case 'raw time ago':
          return $this->dateFormatter->formatTimeDiffSince($value['granularity' => is_numeric($custom_format) ? $custom_format : 2]);

        case 'time ago':
          return $this->t('%time ago', ['%time' => $this->dateFormatter->formatTimeDiffSince($value['granularity' => is_numeric($custom_format) ? $custom_format : 2])]);

        case 'raw time hence':
          return $this->dateFormatter->formatTimeDiffUntil($value['granularity' => is_numeric($custom_format) ? $custom_format : 2]);

        case 'time hence':
          return $this->t('%time hence', ['%time' => $this->dateFormatter->formatTimeDiffUntil($value['granularity' => is_numeric($custom_format) ? $custom_format : 2])]);

        case 'raw time span':
          

  public function preRenderLock($element) {
    if (isset($element['#lock']) && isset($element['#label']) && isset($element['#url'])) {
      /** @var \Drupal\Core\TempStore\Lock $lock */
      $lock = $element['#lock'];
      $age = $this->dateFormatter->formatTimeDiffSince($lock->getUpdated());
      $owner = $this->entityTypeManager->getStorage('user')->load($lock->getOwnerId());
      $username = [
        '#theme' => 'username',
        '#account' => $owner,
      ];
      $element['#markup'] = $this->t('This @label is being edited by user @user, and is therefore locked from editing by others. This lock is @age old. Click here to <a href=":url">break this lock</a>.', [
        '@label' => $element['#label'],
        '@user' => $this->renderer->render($username),
        '@age' => $age,
        ':url' => $element['#url']->toString(),
      ]);
    }
$timestamp$request_time$options$expected],
        [$timestamp$request_time$options + ['return_as_object' => TRUE]new FormattedDateDiff('1 second', 1)],
      ]);

    $request = Request::createFromGlobals();
    $request->server->set('REQUEST_TIME', $request_time);
    // Mocks a the request stack getting the current request.     $this->requestStack->expects($this->any())
      ->method('getCurrentRequest')
      ->willReturn($request);

    $this->assertEquals($expected$this->dateFormatterStub->formatTimeDiffSince($timestamp$options));
    $options['return_as_object'] = TRUE;
    $expected_object = new FormattedDateDiff('1 second', 1);
    $this->assertEquals($expected_object$this->dateFormatterStub->formatTimeDiffSince($timestamp$options));
  }

  /** * Tests the formatTimeDiffSince method. * * @covers ::formatTimeDiffSince */
  public function testFormatTimeDiffSince() {
    
    FieldStorageConfig::loadByName('node', 'comment')->delete();
    $node = $this->drupalCreateNode([
      // This title is required to trigger the custom changed time set in the       // node_test module. This is needed in order to ensure a sufficiently       // large 'time ago' interval that isn't numbered in seconds.       'title' => 'testing_node_presave',
      'status' => 1,
    ]);

    $this->drupalGet('activity');
    $this->assertSession()->pageTextContains($node->label());
    $this->assertSession()->pageTextContains(\Drupal::service('date.formatter')->formatTimeDiffSince($node->getChangedTime()));
  }

  /** * Tests for the presence of nodes on a user's tracker listing. */
  public function testTrackerUser() {
    $this->drupalLogin($this->user);

    $unpublished = $this->drupalCreateNode([
      'title' => $this->randomMachineName(8),
      'uid' => $this->user->id(),
      
public function testSystemDateTokenReplacement() {
    // Set time to one hour before request.     $date = REQUEST_TIME - 3600;

    // Generate and test tokens.     $tests = [];
    $date_formatter = \Drupal::service('date.formatter');
    $tests['[date:short]'] = $date_formatter->format($date, 'short', '', NULL, $this->interfaceLanguage->getId());
    $tests['[date:medium]'] = $date_formatter->format($date, 'medium', '', NULL, $this->interfaceLanguage->getId());
    $tests['[date:long]'] = $date_formatter->format($date, 'long', '', NULL, $this->interfaceLanguage->getId());
    $tests['[date:custom:m/j/Y]'] = $date_formatter->format($date, 'custom', 'm/j/Y', NULL, $this->interfaceLanguage->getId());
    $tests['[date:since]'] = $date_formatter->formatTimeDiffSince($date['langcode' => $this->interfaceLanguage->getId()]);
    $tests['[date:raw]'] = Xss::filter($date);

    // Test to make sure that we generated something for each token.     $this->assertNotContains(0, array_map('strlen', $tests), 'No empty tokens generated.');

    foreach ($tests as $input => $expected) {
      $output = $this->tokenService->replace($input['date' => $date]['langcode' => $this->interfaceLanguage->getId()]);
      $this->assertEquals($expected$outputnew FormattableMarkup('Date token %token replaced.', ['%token' => $input]));
    }
  }

}

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['description'] = [
      '#markup' => '<p>' . $this->t('Cron takes care of running periodic tasks like checking for updates and indexing content for search.') . '</p>',
    ];
    $form['run'] = [
      '#type' => 'submit',
      '#value' => $this->t('Run cron'),
      '#submit' => ['::runCron'],
    ];
    $status = '<p>' . $this->t('Last run: %time ago.', ['%time' => $this->dateFormatter->formatTimeDiffSince($this->state->get('system.cron_last'))]) . '</p>';
    $form['status'] = [
      '#markup' => $status,
    ];

    $cron_url = Url::fromRoute('system.cron', ['key' => $this->state->get('system.cron_key')]['absolute' => TRUE])->toString();
    $form['cron_url'] = [
      '#markup' => '<p>' . $this->t('To run cron from outside the site, go to <a href=":cron" class="system-cron-settings__link">@cron</a>', [':cron' => $cron_url, '@cron' => $cron_url]) . '</p>',
    ];

    if (!$this->moduleHandler->moduleExists('automated_cron')) {
      $form['automated_cron'] = [
        
'#theme' => 'username',
              '#account' => $owner,
            ],
          ],
          'comments' => [
            'class' => ['comments'],
            'data' => $tracker_data[$node->id()]->comment_count ?? 0,
            'data-history-node-last-comment-timestamp' => $tracker_data[$node->id()]->last_comment_timestamp ?? 0,
          ],
          'last updated' => [
            'data' => t('@time ago', [
              '@time' => $this->dateFormatter->formatTimeDiffSince($last_activity),
            ]),
          ],
        ];

        $rows[] = $row;

        // Add node and node owner to cache tags.         $cacheable_metadata->addCacheTags($node->getCacheTags());
        if ($owner) {
          $cacheable_metadata->addCacheTags($owner->getCacheTags());
        }
      }
Home | Imprint | This part of the site doesn't use cookies.