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."

1
  • 1
    you can try \DTMenglishmonthname{\numexpr\month-1\relax}
    – touhami
    Commented Jul 12, 2017 at 15:45

2 Answers 2

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

3
  • What happens if this month is January? Commented Jul 12, 2017 at 20:41
  • 1
    @NicolaTalbot :) Oops. I'll fix soon.
    – Alan Munn
    Commented Jul 12, 2017 at 20:44
  • 1
    @NicolaTalbot Fixed.
    – Alan Munn
    Commented Jul 12, 2017 at 22:39
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}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .