How to Check and Handle Past Dates in Drupal 10 (Timestamp Comparison Guide)

Date comparison is a very common requirement in Drupal applications. Whether you are working with events, subscriptions, custom workflows, approvals, or scheduled content, you often need to determine whether a stored date is in the past.

In this article, we’ll cover the correct and Drupal-recommended way to compare dates using timestamp fields in Drupal 10.

Correct Way to Compare Dates in Drupal 10

Step 1: Get the stored timestamp

If your field type is Timestamp, Drupal already stores it as an integer.

$stored_timestamp = (int) $entity->get('field_date')->value;

This works for:

  • Nodes
  • Users
  • Taxonomy terms
  • Any content entity

Step 2: Get the current timestamp (Drupal way)

$current_timestamp = \Drupal::time()->getRequestTime();

Step 3: Compare the dates

    if ($stored_timestamp < $current_timestamp) {
  \Drupal::messenger()->addWarning(
    t('The selected date is in the past.')
  );
}

This logic can be reused in:

  • Forms
  • Controllers
  • Event subscribers
  • Custom services

Blocking Further Processing (Optional)

If you want to stop execution when the date is in the past:

   if ($stored_timestamp < $current_timestamp) {
  return [
    '#markup' => t('This action is no longer valid because the date has passed.'),
  ];
}

This is useful for:

  • Expired processes
  • Time-limited actions
  • Approval deadlines

Formatting Dates for Display Only 

Formatting should be done after comparison, strictly for UI purposes.

    $formatted_date = date('d M, Y H:i', $stored_timestamp);

Never use formatted values for logical conditions.