Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom date format (callback with php logic)

I want to create a dynamic php date format. Example: show the time of the node if it was published today and only the day/month when older then today. I want this format to be available throughout Drupal like the other predefined date formats in Drupal (not just on theme level).

I found the (D7 only) hook for hook_date_format_types but even that one doesn't seem to allow for a callback where I could define this PHP logic.

Does anyone know which hook would make this possible? Or a module which does this?

like image 398
Albert Skibinski Avatar asked Nov 14 '22 20:11

Albert Skibinski


1 Answers

In Drupal6, format_date() has the dates and times hardcoded. Also, format_date() does not allow callbacks, but it does allow a custom string. That is where you can apply a trick: instead of hardcoding the string in there, you call a function that returns a string.

function mydate_format($timestamp) {
  $now = time();
  if (($now - $timestamp) < (60*60*24)) {
    return "H:i";
  }
  else {
    return "d:m:Y";
  }
}

print format_date($timestamp, 'custom', mydate_format($timestamp));

The second option is to re-define a date-timestamp, but that is both hackish and limited. Date-formats are defined with variable_get(), but don't pass the timestamp along; so your example of switching formats based on the value of timestamp is not possible this way.

In settings.php:

$conf['date_format_long'] = $conf['debug'] ? 'r' : 'l, F j, Y - H:i';

This will switch from one value to another, based on whether your settings.php has a flag "debug" set to TRUE or not. As mentioned: the use for this is limited, since you cannot get any context.

The third alternative is to use Date API which offers onlinle configurable time-formats. But that is both clumsy and insecure (inputting executable PHP in your database). It also depends on a very large module-set. And has the same downside as the first solution: you cannot use format_date, but must use a modified function call, instead of format_date(). See all the options at The Drupal.org date themeing handbook.

GOTCHA In all cases Drupal will not call this function for cached content. If you want to have the dates really dynamic you either need to avoid caching alltogether, or implement the date-formatting in clientside javascript.

TL;DR: You cannot have dynamic date-formats without changing some of the code on theme-level. Using a callback-function to generate the "custom" dateformat is the simplest, working solution.

like image 198
berkes Avatar answered Nov 22 '22 23:11

berkes