You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LaTeX中计算已过年份占比用于合同撰写?

在LaTeX中简便计算当年已度过时间占比的方法

如果要避免手动计算当年总天数、当前日期天数的繁琐步骤,推荐两种更高效的实现方式:

方法1:使用datetime2 + pgfmath包(通用LaTeX编译)

借助datetime2包自动获取系统当前日期的年份和年中天数,结合pgfmath完成计算与小数格式化,无需手动处理闰年判断:

\documentclass{article}
\usepackage{datetime2,pgfmath}

\begin{document}
% 提取当前年份和年中天数
\DTMgetcurrentyear{\currentYear}
\DTMgetcurrentyearday{\currentDayOfYear}

% 自动判断闰年并设置当年总天数
\DTMifleapyear{\currentYear}{%
  \def\totalDays{366}%
}{%
  \def\totalDays{365}%
}

% 计算占比并保留两位小数输出
\pgfmathsetmacro{\timeRatio}{(\currentDayOfYear/\totalDays)*100}
已度过当年时间占比:\pgfmathprintnumber[fixed,precision=2]{\timeRatio}\%
\end{document}

方法2:使用LuaLaTeX直接调用Lua代码(更简洁)

如果你的编译环境支持LuaLaTeX,直接用Lua的日期函数可以一步完成所有逻辑,无需额外LaTeX包:

\documentclass{article}
\begin{document}
已度过当年时间占比:
\directlua{
  local currentDate = os.date("*t")
  -- 判断闰年
  local isLeapYear = (currentDate.year % 4 == 0 and currentDate.year % 100 ~= 0) or (currentDate.year % 400 == 0)
  local totalDays = isLeapYear and 366 or 365
  -- 计算占比并格式化输出两位小数
  local percentage = (currentDate.yday / totalDays) * 100
  tex.print(string.format("%.2f%%", percentage))
}
\end{document}

这两种方法的优势:

  • 自动获取当前日期数据,避免手动输入错误
  • 内置闰年判断逻辑,无需自己编写复杂的条件判断
  • 直接调用格式化函数,轻松实现两位小数的输出要求

内容的提问来源于stack exchange,提问作者user24817815

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 17:44:59