Format dates in Drupal
Drupal provides a clean way of formatting dates any way you want throughout the entire site.
Earlier today, Rachel commented that an upcoming events block on a site we are working on displayed the date in an ugly format. So I changed it and for anyone who is interested, here is the step-by-step process for doing so.
1. Create a date string
Navigate to admin/settings/date-time/formats/add. Click on the 'Add format' sub-tab. Enter a date format string conforming to PHP date function standards. For this project I chose "D, M jS \a\t g:i a" That format string looks intimidating, but it's straight forward. Each character in the format string will be replaced by a date component as defined in this table.- D is replaced by a three character representation of the day. Mon, Tue, Wed...
- M is replaced by a three character representation of the month. Jan, Feb, Mar...
- j is replaced by the day of the month without a leading zero. 1, 2, 9, 10, 11, 31...
- S is replaced by "st", "nd", "rd" or "th" depending on the day of the month. Combined with j you get 1st, 2nd, 3rd, 4th.....
- \a\t is a little more tricky. Because the characters a and t map to date components in the table, these letters are preceded by a backslash to prevent them from being replaced. \a will display as "a" while a will display as lowercase am or pm depending on the time. Here I want to display the word "at" so I wrote \a\t
- g,i,a are used to describe time.
- When a character in a format string does not have a corresponding date component it will display as-is. In the string above, space ( ), comma (,) and colon (:) do not map to a date component so they display as expected.
2. Add a named format (optional)
Navigate to settings/date-time/formats. From this page you will need to create a new format name and select the format you just defined. Here I chose the name "Event Block."3. Select a format
You can map your new format to an existing named format (Long, Medium, Short) or add your own.4. Select the format wherever you want it to display
In our case, we just wanted this format to display on the event block. Since the block is a view, we modify the date field for the view. You can edit the display of date cck fields by navigating to admin/content/node-type/[My Content Type]/display/basic and selecting the format to display for nodes and teasers. You can modify the "submitted by" part of the node two ways. The "submitted by" part of nodes is generated by a theme function called theme_node_submitted. This theme function assumes the "medium" date format. So either set "medium" display to your custom format or override theme_node_submitted in your template.php file.
function mycustomtheme_node_submitted($node) {
return t('Submitted by !username on @datetime',
array(
'!username' => theme('username', $node),
'@datetime' => format_date($node->created, 'myformatname'),
));
}