6

Is there a way to set the commit time with JGit?

I flipped through the API and found that it can only be done by modifying the local system time. I want to implement it through code. And can run normally on the win system.

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
xiao luo
  • 777
  • 1
  • 5
  • 6

2 Answers2

7

The timestamp for a commit can be set with the CommitCommand. Note that name, email, and timestamp must be specified together with a PersonIdent object.

For example:

Date date = ...
PersonIdent defaultCommitter = new PersonIdent(git.getRepository());
PersonIdent committer = new PersonIdent(defaultCommitter, date);
git.commit().setMessage("Commit with time").setCommitter(committer).call();

The defaultCommitter holds name and email as defined in the git config, the timestamp is the current system time. With the second PersonIdent constructor, the name and email are taken from the defaultCommitter and the timestamp is overridden with date.

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
1

In windows the system time can be set by executing the command 'date MM-dd-yy' from the and 'Administrator' command prompt.

Java Snippet for Windows

 //Set the Date 
 SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yy");  
 String setDate = "cmd /C date "+sdf.format(dateToSet);  
 Process dateProc = Runtime.getRuntime().exec(setDate);  
 dateProc.waitFor();//Might take a couple of seconds

 //Set the Time  
 SimpleDateFormat stf = new SimpleDateFormat("HH:mm:ss");  
 String setTime = "cmd /C time "+stf.format(dateToSet);  
 Process timeProc = Runtime.getRuntime().exec(setTime);  
 timeProc.waitFor();//Might take a couple of seconds  

This command can only be executed as an administrator. So you should run the java code with Administrator Privileges.