A new service has been added to Drupal 8.3.x to retrieve the request time or current time. The REQUEST_TIME global constant has also been deprecated, scheduled to be removed before 10.0.0
There are four methods on the service.
Usage
$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();
can be replaced with
$request_time = \Drupal::time()->getRequestTime();
or the equivalent using the injected service, 'datetime.time'.
$request_time_float = $_SERVER['REQUEST_TIME_FLOAT'];
$request_time_float = $requestStack->getCurrentRequest()->server->get('REQUEST_TIME_FLOAT');
$request_time_float = $request->server->get('REQUEST_TIME_FLOAT');
and many instances of
$microtime = microtime();
$microtime = microtime(TRUE);
can be replaced with
$request_time = \Drupal::time()->getRequestMicroTime();
or the equivalent using the injected service.
$time = time();
can be replaced with
$request_time = \Drupal::time()->getCurrentTime();
$microtime = microtime();
$microtime = microtime(TRUE);
can be replaced with
$request_time = \Drupal::time()->getCurrentMicroTime();
or the equivalent using the injected service.
Notes
There are instances when the Drupal kernel has not initialized the request stack, and the request time is still needed. As of https://www.drupal.org/project/drupal/issues/3113476, Time::getRequestTime and Time::getRequestMicrotimeTime will both attempt to pick sane alternatives.
In this case, Time::getRequestTime will first see $_SERVER['REQUEST_TIME'] is available, otherwise it will use Time::getCurrentTime. Time::getRequestMicrotimeTime works in a similar manner for the floating point needs.