Date Localization using version

Part of TutorialAdvanced

Description

Localization example that shows how to use version to compile different versions to use different date formats.

Example

import std.string;

char[] dateString(byte day, byte month, int yr)
{ 
    int twoDigitYr = yr % 100;
    
    version(CANADIAN_ENGLISH)
      return leadingZeros(day, 2) ~ "/" ~ leadingZeros(month, 2) ~ "/" ~ 
        leadingZeros(twoDigitYr, 2);

    version(DANISH)
      return toString(yr) ~ "-" ~ leadingZeros(month, 2) ~ "-" ~ 
        leadingZeros(day, 2);

    version(FINNISH)
      return leadingZeros(day, 2) ~ "." ~ leadingZeros(month, 2) ~ "." ~ 
        toString(yr);

    version(FRENCH)
      return leadingZeros(day, 2) ~ "/" ~ leadingZeros(month, 2) ~ "/" ~ 
        toString(yr);

    version(GERMAN)
      return leadingZeros(day, 2) ~ "." ~ leadingZeros(month, 2) ~ "." ~ 
        leadingZeros(Yr, 2);

    version(ITALIAN)
      return leadingZeros(day, 2) ~ "/" ~ leadingZeros(month, 2) ~ "/" ~ 
        leadingZeros(twoDigitYr, 2);

    version(NORWEGIAN)
      return leadingZeros(day, 2) ~ "-" ~ leadingZeros(month, 2) ~ "-" ~ 
        leadingZeros(twoDigitYr, 2);

    version(SPANISH)
      return leadingZeros(day, 2) ~ "-" ~ leadingZeros(month, 2) ~ "-" ~ 
        leadingZeros(twoDigitYr, 2);

    version(SWEDISH)
      return toString(yr) ~ "-" ~ leadingZeros(month, 2) ~ "-" ~ 
        leadingZeros(day, 2);

    version(GREAT_BRITAIN)
      return leadingZeros(day, 2) ~ "/" ~ leadingZeros(month, 2) ~ "/" ~ 
        leadingZeros(twoDigitYr, 2);

    version(UNITED_STATES)
      return leadingZeros(month, 2) ~ "-" ~ leadingZeros(day, 2) ~ "-" ~ 
        leadingZeros(twoDigitYr, 2);   

    version(THAI)
      return leadingZeros(day, 2) ~ "/" ~ leadingZeros(month, 2) ~ "/" ~ 
        toString(yr);      

    version(ISO_8601)
      return toString(yr) ~ "-" ~ leadingZeros(month, 2) ~ "-" ~ 
        leadingZeros(day, 2);


}


char[] leadingZeros(byte num, byte digits)
/* also in currency.d and with.d */
{ 
    char[] buffer;
    byte diff;
    
    buffer = toString(num);
    if (buffer.length < digits) 
    {
        diff = digits - buffer.length;
        for(int i=0; i < diff; i++)
          buffer = "0" ~ buffer;
    } 
    return buffer;
}


int main()
{ 
    printf("%.*s\n", dateString(24, 8, 2001));
    return 0;
}

Compiling Tips

Compile for the United States locale:

dmd locales.d -version=UNITED_STATES

Compile for the Canadian (English) locale:

dmd locales.d -version=CANADIAN_ENGLISH

Source

These date formats are based on "docs.sun.com: International Language Environments Guide".

Link http://jcc_7.tripod.com/d/tutor/locales2.html
Author jcc7
Date October 7, 2003