Programatically creating date formats
Programatically creating date formats
Brad Blake | Senior Software Architect
August 7, 2012
When creating a new Drupal site, you’ll often come across a need to create new date types and date formats programmatically. However, they’re not exportable, so how can you create and manage them through code? You can still create them in code with a few hooks and statements. If you want to create a new custom date format, that data is stored in the date_formats table. To create a new date format you can follow the example below, changing the PHP date string to the date string of your choosing.
/**
* Create the example date format.
*/
function mymodule_update_7001() {
db_insert('date_formats')
->fields(array(
'format' => 'M. j g:i A T', // PHP Date String
'type' => 'custom', // 'custom'
'locked' => 0, // 0 = user-specified date format
))
->execute();
}
That’s all that you need to create a new date format, and the new format should be available now on the /admin/config/regional/date-time/formats page. To create a new date type ( for example, to use in the format_date() function ), you’ll need a few extra statements. The data for date formats is stored in two places:
- The date_format_type table contains the title and type ( machine name ) of the date format.
- The variable table contains the string format as the value, with a key of the date format machine name.
To programmatically insert a date format in an update hook, you can do:
/**
* Create the example date type.
*/
function mymodule_update_7002() {
db_insert('date_format_type')
->fields(array(
'type' => 'example', // Machine Name
'title' => 'Example', // Display Name
'locked' => 0, // 1 = can't change through UI, 0 = can change
))
->execute();
// Variable name is date_format_MACHINENAME from previous insert
variable_set('date_format_example', 'M. j g:i A T');
}
After running that update hook ( or install hook ), you’ll be able to see your new date type at your /admin/config/regional/date-time page.