February 2010 Archives

Formatting dates in LaTeX with Babel

| No Comments | No TrackBacks

A nice thing about LaTeX is support for automatic date formatting on article’s title pages using the \today macro. It even supports many languages (using Babel or completely language-specific packages). Unfortunately, (as the name suggests) it typesets only the current date, while all other must be written ‘by hand’.

This would not be appropriate way of writing e.g. certificates of attendance for a Polish IB school, where on each page many dates chosen by the school are written in both British English and Polish languages. I wanted to write only a single date in a simple format, like 2010/02/24.

The first solution which I used was a complicated package parsing this date format into separate macros for year, month and day (it also removed leading zeros), and then typesetting them using separate macros for different languages, with 12 macros per language for month names. It had at least the following problems:

  • difficult to understand or maintain macros
  • many per-language macros
  • the output was very similar to the \today macro.

Therefore I have rewritten this package today, using the \today macro after changing the ‘current’ date.

TeX stores the current date in three parameters: \year, \month and \day (The TeXbook, page 273). This trivial macro changes them using the 2010/02/24/ formatted date:

\def\@setcurrentdate#1/#2/#3/{%
  \year=#1%
  \month=#2%
  \day=#3%
  \relax
}

The interface of this macro is strange, but it looks like a simple way of separating parts of the input date. The date-formatting macro will expand its second argument and add the trailing slash (so the whole day will be used, instead of only its first digit) by \expandafter\@setcurrentdate#2/.

Babel provides at least two macros for changing languages: \foreignlanguage and \selectlanguage. The first one has more appropriate interface, but does not change the date format (as stated on page 6 of the Babel manual), so I used the second one.

The whole macro formatting the date has two arguments – language name as used by Babel and the date in slash-separated format. The macro is:

\newcommand{\Date}[2]{{%
    \selectlanguage{#1}%
    \expandafter\@setcurrentdate#2/%
    \today
  }}

(The name is capitalized, since I use it only in some document classes.) I’m not sure if specifying language language for each date is useful (dates are usually in the same language as surrounding text), but it could be trivially removed in useful packages.

I haven’t seen this way of extending LaTeX macros in other code, but it looks like an useful advantage of mutable parameters for ‘constants’ like current time.

liability-deltoid