2

I would like to make the following document print output of 07:00 PM.

\documentclass{article}
\usepackage[calc,english]{datetime2}

\DTMnewtimestyle{ampm}{%
  % \DTMdisplaytime{<hh>}{<mm>}{<ss>}
  \renewcommand{\DTMdisplaytime}[3]{%
    \def\THEHOUR{##1}\def\THEAMPM{AM}% Assume AM
    \ifnum##1>12
      \edef\THEHOUR{\number\numexpr##1-12}% Correct for...
      \edef\THEAMPM{PM}%                    ...PM
    \fi
    \DTMtwodigits{\THEHOUR}% <hh>
    :%
    \DTMtwodigits{##2}% <mm>
    \space
    \THEAMPM% AM/PM
  }%
}

\begin{document}
\DTMsettimestyle{ampm}
\DTMtime{19}
\end{document}
1

Apparently \DTMtime requires an input in the form hh:mm:ss (but just one digit can be used in each part).

You can supply the missing parts with xparse:

\documentclass{article}
\usepackage[calc,english]{datetime2}
\usepackage{xparse}

\NewDocumentCommand{\xDTMtime}{>{\SplitArgument{2}{:}}m}{\xxDTMtime#1}
\NewDocumentCommand{\xxDTMtime}{mmm}{%
  \IfNoValueTF{#2}{%
    \DTMtime{#1:00:00}%
  }{%
    \IfNoValueTF{#3}{%
      \DTMtime{#1:#2:00}%
    }{%
      \DTMtime{#1:#2:#3}%
    }%
  }%
}

\DTMnewtimestyle{ampm}{%
  % \DTMdisplaytime{<hh>}{<mm>}{<ss>}
  \renewcommand{\DTMdisplaytime}[3]{%
    \def\THEHOUR{##1}\def\THEAMPM{AM}% Assume AM
    \ifnum##1>12
      \edef\THEHOUR{\number\numexpr##1-12}% Correct for...
      \edef\THEAMPM{PM}%                    ...PM
    \fi
    \DTMtwodigits{\THEHOUR}% <hh>
    :%
    \DTMtwodigits{##2}% <mm>
    ~%
    \THEAMPM% AM/PM
  }%
}

\begin{document}

\DTMsettimestyle{ampm}

\xDTMtime{19}

\xDTMtime{19:15}

\xDTMtime{19:1:2}

\end{document}

enter image description here

  • After experimenting, I think the output of \xDTMtime{12} should be 12:00 PM instead of 12:00 AM – Diaa May 14 at 18:35
  • 1
    @Diaa Reverse the test: \ifnum##1<12 \else – egreg May 14 at 19:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.