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 Answer 1

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

4
  • After experimenting, I think the output of \xDTMtime{12} should be 12:00 PM instead of 12:00 AM
    – Diaa
    Commented May 14, 2019 at 18:35
  • 1
    @Diaa Reverse the test: \ifnum##1<12 \else
    – egreg
    Commented May 14, 2019 at 19:29
  • How can I store the time in a macro? For instance, I need to save the time 19:1:2 in \mytime then use it later \xDTMtime{\mytime}. I tried \newcommand{\mytime}{19:1:2} but it didn't work for me.
    – Diaa
    Commented Feb 20, 2020 at 23:20
  • 1
    @Diaa \expandafter\xDTMtime\expandafter{\mytime}
    – egreg
    Commented Feb 20, 2020 at 23:28

You must log in to answer this question.

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