我正在努力寻找一种简单的方法来做到这一点。(或者根本)
假设我有以下内容:
时间戳:1697513559
时区:-0500
我怎样才能将其转换为人类可读的格式?
答案1
使用 PGFCalendar 我们可以将任何时间点之后的持续时间变成日期。我们只需要先处理时区,通过操作分钟和小时,然后调整时间点之后的持续时间因此。
它使用了由 PGFCalendar 加载的 PGFInt 模块,但除此之外没有文档记录。(它基本上是 l3int 的克隆。)
除了临时计数之外,\count@
不使用任何其他临时宏。这只能正确处理正纪元值,并且时区对于非负值必须是四位数字,对于负值必须是负数和四位数字。(解析器相对比较笨拙。)
代码
\documentclass{article}
\usepackage{pgfcalendar}
\makeatletter
\newcommand*\epochtodate[8]{%
\pgfintset\count@{\pgfintmod{#1}{86400}}% time
\edef#6{\pgfintdivtruncate{\count@}{3600}}% hour
\edef#7{\pgfintdivtruncate{\count@-#6*3600}{60}}% minute
\edef#8{\pgfinteval{\count@-#6*3600-#7*60}}% second
\pgfintset\count@ {#6\ifnum#2<0 \epochtodate@TZhour #2\else\epochtodate@TZhour +#2\fi}%
\edef#7{\pgfinteval{#7\ifnum#2<0 \epochtodate@TZminute#2\else\epochtodate@TZminute+#2\fi}}%
\epochtodate@check{\count@}{#7}{60}% check timezoned minutes
\edef#6{\the\count@}% hours
\pgfintset\count@{\pgfintdivtruncate{#1}{86400}}% days
\epochtodate@check{\count@}{#6}{24}% check timezoned hours
\epochtodate@zerofill{#6}\epochtodate@zerofill{#7}\epochtodate@zerofill{#8}%
\pgfcalendardatetojulian{1970-01-01+\count@}{\count@}%
\pgfcalendarjuliantodate{\count@}{#3}{#4}{#5}}
\newcommand*\epochtodate@TZhour [5]{#1#2#3}
\newcommand*\epochtodate@TZminute[5]{#1#4#5}
\newcommand*\epochtodate@zerofill[1]{\edef#1{\ifnum#1<10 0\fi#1}}%
\newcommand*\epochtodate@check[3]{%
\ifnum#2<0
\pgfintset#1{#1-1}%
\edef#2{\pgfinteval{#2+#3}}%
\else
\unless\ifnum#2<#3\relax
\pgfintset#1{#1+1}%
\edef#2{\pgfinteval{#2-#3}}%
\fi
\fi}
\makeatother
\begin{document}
\epochtodate{1697513559}{-0500}{\Year}{\Month}{\Date}{\Hour}{\Minute}{\Second}
Epoch 1697513559 in TZ -0500 is \Year-\Month-\Date\ \Hour:\Minute:\Second
\epochtodate{2147483647}{0000}{\Year}{\Month}{\Date}{\Hour}{\Minute}{\Second}
Epoch 2147483647 in TZ 0000 is \Year-\Month-\Date\ \Hour:\Minute:\Second
\end{document}
输出
TZ -0500 中的纪元 1697513559 是 2023-10-16 22:32:39
TZ 0000 中的纪元 2147483647 是 2038-01-19 03:14:07