Programatically creating date formats

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.

Brad Blake
#Drupal | Posted

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.

  1. /**
  2. * Create the example date format.
  3. */
  4. function mymodule_update_7001() {
  5. db_insert('date_formats')
  6. ->fields(array(
  7. 'format' => 'M. j g:i A T', // PHP Date String
  8. 'type' => 'custom', // 'custom'
  9. 'locked' => 0, // 0 = user-specified date format
  10. ))
  11. ->execute();
  12. }

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:

<code>

  1. /**
  2. * Create the example date type.
  3. */
  4. function mymodule_update_7002() {
  5. db_insert('date_format_type')
  6. ->fields(array(
  7. 'type' => 'example', // Machine Name
  8. 'title' => 'Example', // Display Name
  9. 'locked' => 0, // 1 = can't change through UI, 0 = can change
  10. ))
  11. ->execute();
  12.  
  13. // Variable name is date_format_MACHINENAME from previous insert
  14. variable_set('date_format_example', 'M. j g:i A T');
  15. }

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.

Brad Blake