Sunday, June 17, 2012

Relative Date in LaTeX

It's usual, when writing documents, to use sentences like "I have been doing something since MM/YYYY". This is no problem.

If, on the other hand, you want to write a sentence like "I have been doing something for XX years and YY months", every time you update your document you have to remember to change that sentence.

When writing documents in LaTeX, you can work this problem out using a relatively simple command:
\usepackage{datenumber}
\newcounter{dateone}
\newcounter{datetwo}
\newcommand{\difftoday}[3]{%
      \setmydatenumber{dateone}{\the\year}{\the\month}{\the\day}%
      \setmydatenumber{datetwo}{#1}{#2}{#3}%
      \addtocounter{datetwo}{-\thedateone}%
      \the\numexpr-\thedatetwo/365\relax\space years and
      \the\numexpr(-\thedatetwo - (-\thedatetwo/365)*365)/30\relax\space months
} 

The package datenumber allows to  handle dates as timestamps, therefore we can use counters to perform operations on them (namely, dateone and datetwo). We set dateone to the current date, and datetwo to the user-specified date.

Then, in our document we can use:
\difftoday{2002}{01}{01}

And, say, if we are on March 3rd, 2012, it will render as "10 years and 2 months".

No comments:

Post a Comment