Over the years of maintaining Drupal websites I noticed that a lot of developers – and themers – hard code date and time formats. I know this may sound like a rant, but I would like to demonstrate an easier and cleaner way of creating and managing date and time formats.
How often have you seen this
format_date($node->changed, 'custom', 'd-m-Y'); inside template files? I'm not saying it's wrong to use the
format_date()(API Documentation) function, but if you are defining the date and time format in ten different templates it'll be very difficult to manage if you want to change the formats – because remember clients love to change things just before a launch.
A simple solution to all this madness is to define a Date and Time format and type.
Let's create a date and time type called "Blog Created Short".
Go to Configuration -> "Date and time" (admin/config/regional/date-time).
Go to the "Formats" tab and click on "Add format", define the date/time format and then click on "Add format". For this example enter in "d-m-Y".
Now that our format has been created, go back to the types page and click on "Add date type". Enter in "Blog Created Short" as the "Date type" and select the format that you want to use.
See how simple it is to create a date and time type and best of all we’ll be able to reuse the same "Blog Created Short" type in many places. If you need to output a date via the
format_date() function, just specify the type.
You can also reuse the type within Views. If you add the "Content: Post date" – or any timestamp type field – field, you’ll be able to reuse any date and time types.
If you have any questions please leave a comment.