1

In my custom module (.module) file, I am using:

$current_time = \Drupal::time()->getCurrentTime();
date_default_timezone_set('GMT');

to get the current date... However, the date value is returned in int A Unix timestamp like: 1556582116

I have tried so far something like:

$current_time = \Drupal::time()->getCurrentTime();
$timenow = $current_time->format('Y-m-d H:i:s');

or

$current_time = \Drupal::time()->getCurrentTime('d');

to get only the day value... but with no success

How can I return the date value in the format of: D/M/Y like: 30/04/2019 or 30/Apr/19

2 Answers 2

5

You can do that with simple PHP function. Is there any specific reason you want a drupal function ? If not then you can use PHP's date() function.

$current_time = \Drupal::time()->getCurrentTime();

//To return 30/04/2019
$date_output = date('d/m/Y', $current_time); 

//To return 30/Apr/19
$date_output = date('d/M/y', $current_time); 
1
  • 2
    You should use Drupal date services so the set application timezone is accounted for.
    – Kevin
    Commented Jul 11, 2021 at 18:52
12

You can format the current date using the below solutions.

Drupal 8:

//format date in 30/04/2019    
$current_time = \Drupal::time()->getCurrentTime('d');    
$date_today = format_date($current_time, 'custom', 'd/m/Y');    

//format date in 30/Apr/2019    
$current_timestamp = \Drupal::time()->getCurrentTime();    
$todays_date = format_date($current_timestamp, 'custom', 'd/M/Y');

Drupal 9:

//format date in 30/04/2019    
$current_time = \Drupal::time()->getCurrentTime('d');    
$date_today = \Drupal::service('date.formatter')->format($current_time, 'custom', 'd/m/Y');

//format date in 30/Apr/2019    
$current_timestamp = \Drupal::time()->getCurrentTime();    
$todays_date = \Drupal::service('date.formatter')->format($current_timestamp, 'custom', 'd/M/Y');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.