How do I split a date?
For a simple split function you can use a delimited macro. You could simply do this:
\def\mysplit#1.#2.#3.{\def\myday{#1}\def\mymonth{#2}\def\myyear{#3}}
\def\splitdate#1{\expandafter\mysplit#1.}
\documentclass{article}
\begin{document}
\noindent We have the date: 23.01.2012 \splitdate{23.01.2012}\\
Day: \myday\\
Month: \mymonth\\
Year: \myyear
\end{document}
result:
Note that right now this approach lacks any kind of error handling for wrongly formatted output.
Edit: Some additional explanation regarding the \expandafter
.
The difference is the added \expandafter
. What happens when using \splitdate{<argument>}
then \mysplit#1
is replaced by \mysplit<argument to \splitdate>
. When <argument to \splitdate>
is not a date formatted like dd.mm.yyyy
but a macro \mydate
which is defined as \def\mydate{10.10.2010}
then \mysplit\mydate
does not match the definition of \mysplit
(since that needs arguments delimited by .
). When we use \expandafter
, \mysplit
is left untouched and \mydate
is expanded first. This leads to \mysplit10.10.2010
, then \mysplit
is expanded and the arguments match the definition. When we have an additional layer, like \def\mydate{12.12.2012}\def\otherdate{\mydate}
then this will still fail since \expandafter
will only expand the token once. We could make this work as well, by adding a local expanded definition which we use. The complete code would then look like this:
\def\mysplit#1.#2.#3.{\gdef\myday{#1}\gdef\mymonth{#2}\gdef\myyear{#3}}
\def\splitdate#1{{\edef\x{#1}\expandafter\mysplit\x.}}
\documentclass{article}
\begin{document}
\def\mydate{23.01.2012}
\def\deepdate{\mydate}
\noindent We have the date: 23.01.2012 \splitdate{\deepdate}\\
Day: \myday\\
Month: \mymonth\\
Year: \myyear
\end{document}
Note that we had to change the definition of \myday
etc. to global.
You could also use \StrBefore
, \StrBetween
, and \StrBehind
from the the xstring
package:
\documentclass{article}
\usepackage{xstring}
\newcommand*{\ExtractDay}[1]{\StrBefore[1]{#1}{.}}%
\newcommand*{\ExtractMonth}[1]{\StrBetween[1,2]{#1}{.}{.}}%
\newcommand*{\ExtractYear}[1]{\StrBehind[2]{#1}{.}}%
\newcommand*{\MySplit}[1]{%
\def\MyDay{\ExtractDay{#1}}%
\def\MyMonth{\ExtractMonth{#1}}%
\def\MyYear{\ExtractYear{#1}}%
}%
\begin{document}
\noindent We have the date: 23.01.2012\\
Day: \ExtractDay{23.01.2012}\\
Month: \ExtractMonth{23.01.2012}\\
Year: \ExtractYear{23.01.2012}
\bigskip
\noindent If you prefer to have separate macros define for each component
\noindent We have the date: 23.01.2012 \MySplit{23.01.2012}\\
Day: \MyDay\\
Month: \MyMonth\\
Year: \MyYear
\end{document}