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

如何使用JGit在本地Git仓库提交时设置过去的指定日期?

在JGit中指定过去日期提交代码的正确方法

你当前代码的问题是误用了PersonIdent的构造函数——把日期字符串当作邮箱参数传入,而非设置提交时间戳,JGit因此默认使用系统当前时间生成提交记录。

正确实现步骤

  1. 将目标日期字符串解析为Date对象,注意设置时区避免偏差
  2. 使用带时间参数的PersonIdent构造函数创建作者/提交者信息
  3. 执行提交时传入上述PersonIdent对象

完整代码示例

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.PersonIdent;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class GitCommitWithOldDate {
    public static void main(String[] args) throws Exception {
        // 初始化本地Git仓库实例
        Git git = Git.open(new java.io.File("/path/to/your/local/repo"));
        
        // 指定目标提交日期
        String targetDateStr = "2023-03-01";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 统一使用UTC时区避免跨环境时区差异
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date targetDate = dateFormat.parse(targetDateStr);

        // 创建带指定时间的作者和提交者信息
        PersonIdent author = new PersonIdent(
            "X", 
            "your-email@example.com", 
            targetDate, 
            TimeZone.getTimeZone("UTC")
        );
        PersonIdent committer = new PersonIdent(
            "X", 
            "your-email@example.com", 
            targetDate, 
            TimeZone.getTimeZone("UTC")
        );

        // 执行提交操作
        git.commit()
            .setAuthor(author)
            .setCommitter(committer)
            .setMessage("Modified temp.txt")
            .call();
        
        git.close();
    }
}

关键说明

  • PersonIdent必须使用包含时间参数的重载构造函数,其中when参数为指定的提交日期,tz参数对应时区,建议用UTC保证跨环境一致性
  • 邮箱参数不可省略,Git要求提交记录的作者/提交者必须包含邮箱(可使用虚构邮箱,但格式需符合xxx@xxx.xxx规范)
  • 解析日期时务必设置时区,否则可能因本地时区与Git仓库时区不一致导致日期显示错误

提交完成后,通过git log命令即可看到提交日期已变为你指定的过去日期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 00:33:25