[Tex/LaTex] Extract number from string and compare problem

etoolboxstringsxstring

I try to extract the year, month and day from a string and write different text depending on the given date. I thought I could use xstring and etoolbox, but I can'st get it to work. Here's the code snippet:

\usepackage{xstring}
\usepackage{etoolbox}

\begin{document}
\newcommand{\Datum}{04.12.2011}

\newcommand{\Jahr}{\StrBehind[2]{\Datum}{.}}
\newcommand{\Monat}{\StrBetween[1,2]{\Datum}{.}{.}}
\newcommand{\Tag}{\StrBefore[1]{\Datum}{.}}

Jahr: \Jahr

\ifnumcomp{\Jahr}{=}{2011}{Jahr eq 2011}{Jahr neq 2011}

Which gives the following error:

pdflatex> ! Missing number, treated as zero.
pdflatex> <to be read again> 
pdflatex>                    \let 
pdflatex> l.11 {305}
pdflatex>           
pdflatex> ! Missing = inserted for \ifnum.
pdflatex> <to be read again> 

But \Jahr seems to correctly contain 2011.

Best Answer

Please avoid providing code snippets; instead, do create a complete MWE.

You are passing the complete xstring-test to ifnumcomp. That fails. You can save the the result of the xstring-test by the optional argument of \StrBehind and pass this to \ifnumcomp:

\documentclass{article}
\usepackage{xstring}
\usepackage{etoolbox}

\begin{document}
\newcommand{\Datum}{04.12.2011}

\StrBehind[2]{\Datum}{.}[\Jahr]
\StrBetween[1,2]{\Datum}{.}{.}[\Monat]
\StrBefore[1]{\Datum}{.}[\Tag]

Jahr: \Jahr

\ifnumcomp{\Jahr}{=}{2011}{Jahr eq 2011}{Jahr neq 2011}
\end{document}

Maybe you want to combine the output and the test you can use:

\documentclass{article}
\usepackage{xstring}
\usepackage{etoolbox}
\makeatletter
\newcommand\Datum[1]{\@datum{#1}\@executetest{#1}}
\def\@datum#1{#1}
\def\@executetest#1{%
\StrBehind[2]{#1}{.}[\Jahr]
\StrBetween[1,2]{#1}{.}{.}[\Monat]
\StrBefore[1]{#1}{.}[\Tag]
}
\begin{document}
\Datum{04.12.2011}

Jahr: \Jahr

\ifnumcomp{\Jahr}{=}{2011}{Jahr eq 2011}{Jahr neq 2011}
\end{document}
Related Question