Community Documentation

format_date

5 common.inc format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL)
6 common.inc format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL)
7 common.inc format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL)
8 common.inc format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL)

Formats a date, using a date type or a custom date format string.

Parameters

$timestamp: A UNIX timestamp to format.

$type: (optional) The format to use, one of:

  • 'short', 'medium', or 'long' (the corresponding built-in date formats).
  • The name of a date type defined by a module in hook_date_format_types(), if it's been assigned a format.
  • The machine name of an administrator-defined date format.
  • 'custom', to use $format.

Defaults to 'medium'.

$format: (optional) If $type is 'custom', a PHP date format string suitable for input to date(). Use a backslash to escape ordinary text, so it does not get interpreted as date format characters.

$timezone: (optional) Time zone identifier, as described at http://php.net/manual/en/timezones.php Defaults to the time zone used to display the page.

$langcode: (optional) Language code to translate to. Defaults to the language used to display the page.

Return value

A translated date string in the requested format.

Related topics

▾ 55 functions call format_date()

CommentPreviewTest::testCommentEditPreviewSave in modules/comment/comment.test
Test comment edit, preview, and save.
comment_admin_overview in modules/comment/comment.admin.inc
Form builder for the comment overview administration form.
comment_form in modules/comment/comment.module
Generate the basic commenting form, for appending to a node or display on a separate page.
comment_tokens in modules/comment/comment.tokens.inc
Implements hook_tokens().
dblog_event in modules/dblog/dblog.admin.inc
Menu callback; displays details about a log message.
dblog_overview in modules/dblog/dblog.admin.inc
Menu callback; displays a listing of log messages.
DrupalWebTestCase::drupalCreateNode in modules/simpletest/drupal_web_test_case.php
Creates a node based on default settings.
FileTokenReplaceTestCase::testFileTokenReplacement in modules/file/tests/file.test
Creates a file, then tests the tokens generated from it.
FormatDateUnitTest::testAdminDefinedFormatDate in modules/simpletest/tests/common.test
Test admin-defined formats in format_date().
FormatDateUnitTest::testFormatDate in modules/simpletest/tests/common.test
Tests for the format_date() function.
form_process_date in includes/form.inc
Roll out a single date element.
hook_tokens in modules/system/system.api.php
Provide replacement values for placeholder tokens.
hook_watchdog in modules/system/system.api.php
Log an event message
LocaleDateFormatsFunctionalTest::testLocalizeDateFormats in modules/locale/locale.test
Functional tests for localizing date formats.
locale_date_format_form in modules/locale/locale.admin.inc
Provide date localization configuration options to users.
NodeRevisionsTestCase::testRevisions in modules/node/node.test
Check node revision related operations.
node_admin_nodes in modules/node/node.admin.inc
Form builder: Builds the node administration overview.
node_form in modules/node/node.pages.inc
Generate the node add/edit form array.
node_object_prepare in modules/node/node.module
Prepares a node object for editing.
node_revision_delete_confirm in modules/node/node.pages.inc
node_revision_delete_confirm_submit in modules/node/node.pages.inc
node_revision_overview in modules/node/node.pages.inc
Generate an overview table of older revisions of a node.
node_revision_revert_confirm in modules/node/node.pages.inc
Ask for confirmation of the reversion to prevent against CSRF attacks.
node_revision_revert_confirm_submit in modules/node/node.pages.inc
node_show in modules/node/node.module
Generate an array which displays a node detail page.
node_tokens in modules/node/node.tokens.inc
Implements hook_tokens().
poll_votes in modules/poll/poll.pages.inc
Callback for the 'votes' tab for polls you can see other votes on
StatisticsTokenReplaceTestCase::testStatisticsTokenReplacement in modules/statistics/statistics.test
Creates a node, then tests the statistics tokens generated from it.
statistics_access_log in modules/statistics/statistics.admin.inc
Menu callback; Displays recent page accesses.
statistics_node_tracker in modules/statistics/statistics.pages.inc
statistics_recent_hits in modules/statistics/statistics.admin.inc
Menu callback; presents the "recent hits" page.
statistics_tokens in modules/statistics/statistics.tokens.inc
Implements hook_tokens().
statistics_user_tracker in modules/statistics/statistics.pages.inc
system_add_date_format_type_form in modules/system/system.admin.inc
Add new date type.
system_configure_date_formats_form in modules/system/system.admin.inc
Allow users to add additional date formats.
system_date_delete_format_form in modules/system/system.admin.inc
Menu callback; present a form for deleting a date format.
system_date_delete_format_form_submit in modules/system/system.admin.inc
Delete a configured date format.
system_date_time_formats in modules/system/system.admin.inc
Displays the date format strings overview page.
system_date_time_lookup in modules/system/system.admin.inc
Return the date for a given format string via Ajax.
system_date_time_settings in modules/system/system.admin.inc
Form builder; Configure the site date and time settings.
system_time_zones in modules/system/system.module
Generate an array of time zones and their local time&date.
system_tokens in modules/system/system.tokens.inc
Implements hook_tokens().
system_token_info in modules/system/system.tokens.inc
Implements hook_token_info().
template_preprocess_aggregator_item in modules/aggregator/aggregator.pages.inc
Processes variables for aggregator-item.tpl.php.
template_preprocess_comment in modules/comment/comment.module
Process variables for comment.tpl.php.
template_preprocess_node in modules/node/node.module
Process variables for node.tpl.php
template_preprocess_search_result in modules/search/search.pages.inc
Process variables for search-result.tpl.php.
theme_update_report in modules/update/update.report.inc
Returns HTML for the project status report.
theme_update_version in modules/update/update.report.inc
Returns HTML for the version display of a project.
TokenReplaceTestCase::testSystemDateTokenReplacement in modules/system/system.test
Tests the generation of all system date tokens.
TokenReplaceTestCase::testTokenReplacement in modules/system/system.test
Creates a user and a node, then tests the tokens generated from them.
TriggerActionTestCase::generateTokenExpandedComparison in modules/trigger/trigger.test
Generates a comparison message to match the pre-token-replaced message.
UserTokenReplaceTestCase::testUserTokenReplacement in modules/user/user.test
Creates a user, then tests the tokens generated from it.
user_pass_reset in modules/user/user.pages.inc
Menu callback; process one time login link and redirects to the user page on success.
user_tokens in modules/user/user.tokens.inc
Implements hook_tokens().

File

includes/common.inc, line 1885
Common functions that many Drupal modules will need to reference.

Code

<?php
function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
  // Use the advanced drupal_static() pattern, since this is called very often.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['timezones'] = &drupal_static(__FUNCTION__);
  }
  $timezones = &$drupal_static_fast['timezones'];

  if (!isset($timezone)) {
    $timezone = date_default_timezone_get();
  }
  // Store DateTimeZone objects in an array rather than repeatedly
  // constructing identical objects over the life of a request.
  if (!isset($timezones[$timezone])) {
    $timezones[$timezone] = timezone_open($timezone);
  }

  // Use the default langcode if none is set.
  global $language;
  if (empty($langcode)) {
    $langcode = isset($language->language) ? $language->language : 'en';
  }

  switch ($type) {
    case 'short':
      $format = variable_get('date_format_short', 'm/d/Y - H:i');
      break;

    case 'long':
      $format = variable_get('date_format_long', 'l, F j, Y - H:i');
      break;

    case 'custom':
      // No change to format.
      break;

    case 'medium':
    default:
      // Retrieve the format of the custom $type passed.
      if ($type != 'medium') {
        $format = variable_get('date_format_' . $type, '');
      }
      // Fall back to 'medium'.
      if ($format === '') {
        $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
      }
      break;
  }

  // Create a DateTime object from the timestamp.
  $date_time = date_create('@' . $timestamp);
  // Set the time zone for the DateTime object.
  date_timezone_set($date_time, $timezones[$timezone]);

  // Encode markers that should be translated. 'A' becomes '\xEF\AA\xFF'.
  // xEF and xFF are invalid UTF-8 sequences, and we assume they are not in the
  // input string.
  // Paired backslashes are isolated to prevent errors in read-ahead evaluation.
  // The read-ahead expression ensures that A matches, but not \A.
  $format = preg_replace(array('/\\\\\\\\/', '/(?<!\\\\)([AaeDlMTF])/'), array("\xEF\\\\\\\\\xFF", "\xEF\\\\\$1\$1\xFF"), $format);

  // Call date_format().
  $format = date_format($date_time, $format);

  // Pass the langcode to _format_date_callback().
  _format_date_callback(NULL, $langcode);

  // Translate the marked sequences.
  return preg_replace_callback('/\xEF([AaeDlMTF]?)(.*?)\xFF/', '_format_date_callback', $format);
}
?>

Comments

Options are actually small, medium, large

If you can't get this function to work, try using small, medium, and large for the date formats. I don't know if this is an error in documentation or because I'm running the date module.

for Drupal 6.x

It looks like the documentation on this page applies to the 7.x function which takes short, medium and long. The 6.x function takes small, medium and large, as aiquandol points out.

Maybe the 6 and 7 documentation should be separated?

Login or register to post comments