public function Time::getRequestTime in Drupal 10
Same name and namespace in other branches
- 8 core/lib/Drupal/Component/Datetime/Time.php \Drupal\Component\Datetime\Time::getRequestTime()
- 9 core/lib/Drupal/Component/Datetime/Time.php \Drupal\Component\Datetime\Time::getRequestTime()
Returns the timestamp for the current request.
This method should be used to obtain the current system time at the start of the request. It will be the same value for the life of the request (even for long execution times).
If the request is not available it will fallback to the current system time.
This method can replace instances of
$request_time = $_SERVER['REQUEST_TIME'];
$request_time = REQUEST_TIME;
$request_time = $requestStack
->getCurrentRequest()->server
->get('REQUEST_TIME');
$request_time = $request->server
->get('REQUEST_TIME');
and most instances of
$time = time();
with
$request_time = \Drupal::time()
->getRequestTime();
or the equivalent using the injected service.
Using the time service, rather than other methods, is especially important when creating tests, which require predictable timestamps.
Return value
int A Unix timestamp.
Overrides TimeInterface::getRequestTime
See also
\Drupal\Component\Datetime\TimeInterface::getRequestMicroTime()
\Drupal\Component\Datetime\TimeInterface::getCurrentTime()
\Drupal\Component\Datetime\TimeInterface::getCurrentMicroTime()
1 method overrides Time::getRequestTime()
- TestTime::getRequestTime in core/
modules/ update/ tests/ modules/ update_test/ src/ Datetime/ TestTime.php - Returns the timestamp for the current request.
File
- core/
lib/ Drupal/ Component/ Datetime/ Time.php, line 32
Class
- Time
- Provides a class for obtaining system time.
Namespace
Drupal\Component\DatetimeCode
public function getRequestTime() {
$request = $this->requestStack
->getCurrentRequest();
if ($request) {
return $request->server
->get('REQUEST_TIME');
}
// If this is called prior to the request being pushed to the stack fallback
// to built-in globals (if available) or the system time.
return $_SERVER['REQUEST_TIME'] ?? $this
->getCurrentTime();
}