我是 LaTeX 新手,需要帮助。
我想将此日期格式的输入转换20161027
为此输出:
“星期四,2016 年 10 月 27 日”
我尝试了各种包裹xstring
和datenumber
。
以下代码运行出错。
\documentclass[11pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage[ngerman]{datenumber}
\usepackage{xstring}
\usepackage[left=2.00cm, right=2.50cm, top=6.50cm, bottom=3.00cm]{geometry}
\newcommand{\shortdat}{\datedayname {,} \thedateday.\thedatemonth.\thedateyear}
\newcommand{\stringtosub}{\nul}
\newcommand{\substring}[2][1]{
\ifx\\#2\\
{\stringtosub}
\else
\StrMid{\stringtosub}{#1}{#2}
\fi
}
\newcommand{\operation}[1]{
\renewcommand{\stringtosub}{#1}
\substring[1]{4}.\substring[5]{6}.\substring[7]{8}
\setdate{\substring[1]{4}}{\substring[5]{6}}{\substring[7]{8}}
\shortdat
}
\begin{document}
first \operation{20161025}
\\
next \operation{20161027}
\end{document}
我该如何解决?
答案1
这是一个使用选项datetime2
:
\documentclass{article}
\usepackage[calc,english]{datetime2}
\makeatletter
\newcommand{\operation}[1]{\@operation #1\relax}
\def\@operation #1#2#3#4#5#6#7#8\relax{{%
\DTMsavedate{saveddate}{#1#2#3#4-#5#6-#7#8}%
\DTMsetdatestyle{mydate}% Set new date style
\DTMusedate{saveddate}% Set date
}}
\DTMnewdatestyle{mydate}{%
% #1 = year
% #2 = month
% #3 = day
% #4 = day of week
\renewcommand{\DTMdisplaydate}[4]{%
\DTMweekdayname{##4}, \DTMtwodigits{##3}.\DTMtwodigits{##2}.\number##1}%
}
\begin{document}
first \operation{20161025}
next \operation{20161027}
\end{document}
该实现假定您的输入\operation
始终是这种形式YYYYMMDD
(换句话说,月份和日期的两位数表示)。
答案2
它更简单:只需将数字作为宏参数吸收。
\documentclass[11pt,a4paper]{article}
\usepackage[ngerman]{datenumber}
\newcommand{\operation}[1]{\splitdate#1}
\newcommand{\splitdate}[8]{%
\begingroup % to keep \setdate local
\setdate{#1#2#3#4}{#5#6}{#7#8}%
\datedayname,~#7#8.#5#6.#1#2#3#4%
% if you want to omit leading zeros use the line below
%\datedayname,~\number#7#8.\number#5#6.#1#2#3#4%
\endgroup
}
\begin{document}
first \operation{20161025}
next \operation{20161027}
\end{document}
如果您还想检查参数的长度是否为八个字符,您可以执行以下操作:
\documentclass[11pt,a4paper]{article}
\usepackage{xparse}
\usepackage[ngerman]{datenumber}
\ExplSyntaxOn
\NewDocumentCommand{\operation}{m}
{
\int_compare:nTF { \tl_count:n { #1 } = 8 }
{
\crss_print_date:nnnnnnnn #1
}
{
\errmessage{Invalid~date}
ERR-#1-ERR
}
}
\cs_new_protected:Nn \crss_print_date:nnnnnnnn
{
\group_begin:
\setdate{#1#2#3#4}{#5#6}{#7#8}
\datedayname,~#7#8.#5#6.#1#2#3#4
% if you want to omit leading zeros use the line below
%\datedayname,~\number#7#8.\number#5#6.#1#2#3#4
\group_end:
}
\ExplSyntaxOff
\begin{document}
first \operation{20161025}
next \operation{20161027}
error \operation{1233}
error \operation{123456789}
\end{document}
月份和日期的无效值将通过 发出信号datenumber
。