怎样修改 Git 提交的 AuthorDate 或 CommitDate?

May 8, 2025

假设你周一提交了一个修复,维护者周五用 cherry-pick 把它合入发布分支。发布分支上的这条提交通常会显示两个日期:作者日期是周一,即你最初记录改动的时间;提交者日期是周五,即维护者创建这个副本的时间。运行下面的命令可以同时查看最近一次提交的两个时间戳。

git log -1 --format=fuller

怎样只改最近一次提交的一个日期?

Git 将这两个字段分别标为 AuthorDate 和 CommitDate。手册对 --date 的说明是 “Override the author date used in the commit.”,也就是覆盖本次提交使用的作者日期。1 用 amend 修改提交时,Git 通常会把新提交的提交者日期设为当前时间。动手前先确认暂存区干净,以免把文件改动也带进去。

只改 AuthorDate 时,先用 %cI 读取原有的提交者日期(包含时区的 ISO 8601 格式),再在 amend 时将它传回 Git。

GIT_COMMITTER_DATE="$(git show -s --format=%cI HEAD)" \
  git commit --amend --no-edit --date="2025-05-05T09:30:00+08:00"

只改 CommitDate 时,为这条命令设置 GIT_COMMITTER_DATE。常规的 amend 会沿用原作者和作者日期。2

GIT_COMMITTER_DATE="2025-05-07T16:00:00+08:00" git commit --amend --no-edit

若要显式指定两个日期,可以在第二条命令上加 --date="2025-05-05T09:30:00+08:00"。再次运行 git log -1 --format=fuller 核对两个值。

更早的提交怎么改?

如果分支历史是线性的,可以运行 git rebase -i abc1234^,把 abc1234 换成目标提交的哈希。脱字符选中目标提交的父提交,因此重放列表会从目标提交本身开始。若要修改仓库中的第一条提交,请用 git rebase -i --root。3

将目标所在行的 pick 改成 edit 并保存。等 Git 暂停后,执行所需的 amend 命令,核对两个日期,再运行 git rebase --continue。改动时间戳会让提交获得新的哈希。后续每条被重放的提交也会因为父提交发生变化而获得新的哈希,提交者日期通常也会更新。重写共享分支之前,请先和协作者商量。

Footnotes

  1. Git Project.(无日期)。git-commit,Options,--date=<date>。Git 文档。选项说明。 ↩

  2. Pladijs, P.(2011 年 2 月 16 日)。对 How can one change the timestamp of an old commit in Git? 的回答。Stack Overflow。分别修改作者日期和提交者日期的例子。 ↩

  3. Git Project.(无日期)。git-rebase,Interactive mode。Git 文档。在 rebase 过程中编辑提交。 ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-05-08). 怎样修改 Git 提交的 AuthorDate 或 CommitDate?. https://caiborui.com/blog/2025-05-08-en-change-git-author-and-committer-dates-zhtrans

@misc{borui2025-3d016869,
  author = {borui},
  title = {{怎样修改 Git 提交的 AuthorDate 或 CommitDate?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-05-08-en-change-git-author-and-committer-dates-zhtrans}
}