3

Is is possible to use datetime2 to calculate the previous month from \today? (Alternatively another package).

I've found some solutions that use negative deduction of days, but that would cause problems around the end of the month.

Example: \today = 12-JUL-2017

Wanted output: "Today is 12-JUL-2017. Last month was June."

Alan Munn
  • 218,180

2 Answers2

3

You can save the current date using \DTMsavenow and then use \DTMfetchmonth and DTMmonthname or its equivalents to calculate the previous (or next) month. I've added both a \lastmonth and \nextmonth version.

\documentclass{article}
\usepackage[calc]{datetime2}
\usepackage{ifthen}
\newcommand\lastmonth[1]{\ifthenelse{\DTMfetchmonth{#1}=1}
    {\DTMmonthname{12}}{\DTMmonthname{\numexpr\DTMfetchmonth{#1}-1\relax}}}
\newcommand\nextmonth[1]{\ifthenelse{\DTMfetchmonth{#1}=12
    {\DTMmonthname{1}}{\DTMmonthname{\numexpr\DTMfetchmonth{#1}+1\relax}}}
\begin{document}
\DTMsavenow{today}
\DTMsavedate{jan20}{2017-01-20}
Today is \today.
Last month was \lastmonth{today}.

Today is \DTMusedate{jan20}.
Last month was \lastmonth{jan20}.

Next month is \nextmonth{jan20}.
\end{document}

output of code

Alan Munn
  • 218,180
2

You can also do this without any packages. You can define your own \lastmonth macro:

enter image description here

\documentclass{article}

% \setdate{<day>}{<month>}{<year>}
\newcommand{\setdate}[3]{\day=#1\month=#2\year=#3\relax}%
\newcommand{\lastmonth}{%
  \ifcase\month\or%  0
    December\or   %  1
    January\or    %  2
    February\or   %  3
    March\or      %  4
    April\or      %  5
    May\or        %  6
    June\or       %  7
    July\or       %  8
    August\or     %  9
    September\or  % 10
    October\or    % 11
    November\fi   % 12
}

\begin{document}

Today is \today.
Last month was \lastmonth.

\setdate{20}{1}{2017}%
Today is \today.
Last month was \lastmonth.

\end{document}
Werner
  • 603,163