Date Localization

February 3
blog author

rllabore

Developer

I am working on a multilingual site which requires me to localize the date format for each enabled language. Here are the available languages and their date formats: * Spanish(es) - j de F, Y * German(de) - j. F Y * Japanese(ja) - Y年n月j日 In order to achieve this, I have enabled date_locale and its dependencies(date_api, locale). Here are the steps that I took in order to localize the date format: 1) Navigate to "Site Configuration" > "Date and time" > "Formats" > "Add Format". 2) Create the custom format for Spanish and Japanese languages. 3) Navigate to "Site Configuration" > "Date and time" > "Locale date settings". 4) For each language available, set the long, medium and short date format. Here is the script that I used to propagate the changes from my local machine to different site instances.

$custom_formats = array(
  'Y\年n\月j\日',
  'j \d\e F, Y - H:i',
  'l, j \d\e F, Y - H:i',
  'j \d\e M Y - g:ia',
);

$spanish_date_formats = array(
  array(
    'type'  => 'long',
    'format' => 'l, j \d\e F, Y - H:i',
  ),
  array(
    'type'  => 'medium',
    'format' => 'j \d\e F, Y - H:i',
  ),
  array(
    'type'  => 'short',
    'format' => 'j \d\e M Y - g:ia',
  ),
);

$german_date_formats = array(
  array(
    'type'  => 'long',
    'format' => 'j. F Y - G:i',
  ),
  array(
    'type'  => 'medium',
    'format' => 'j. F Y - G:i',
  ),
  array(
    'type'  => 'short',
    'format' => 'j. F Y - G:i',
  ),
);

$japanese_date_formats = array(
  array(
    'type'  => 'long',
    'format' => 'Y\年n\月j\日',
  ),
  array(
    'type'  => 'medium',
    'format' => 'Y\年n\月j\日',
  ),
  array(
    'type'  => 'short',
    'format' => 'Y\年n\月j\日',
  ),
);

// create custom date formats
foreach($custom_formats as $k => $_format) {
  $format           = array();
  $format['format'] = $_format;
  $format['type']   = 'custom';
  $format['locked'] = 0;
  $format['is_new'] = 1;
		
  date_format_save($format);
}

// localize date format
foreach($spanish_date_formats as $es_format) {
		
  $langcode = 'es';
  $type     = $es_format['type'];
  $format   = $es_format['format'];
  date_locale_locale_format_save($langcode, $type, $format);
}
	
foreach($german_date_formats as $de_format) {
		
  $langcode = 'de';
  $type     = $de_format['type'];
  $format   = $de_format['format'];
  date_locale_locale_format_save($langcode, $type, $format);
}
	
foreach($japanese_date_formats as $ja_format) {
		
  $langcode = 'ja';
  $type     = $ja_format['type'];
  $format   = $ja_format['format'];
  date_locale_locale_format_save($langcode, $type, $format);
}