Changing the timestamp of an old Git commit is generally not recommended, as it alters the commit history and may affect other collaborators' work. However, in certain special cases, such as correcting incorrect timestamp settings, it may be necessary.
Here are the steps to change the timestamp of old Git commits:
-
Using
git rebasecommand: To change the timestamp of a specific commit, use thegit rebasecommand in interactive mode. For example, to modify one of the last three commits, execute:shellgit rebase -i HEAD~3 -
Selecting the commit to edit: In the editor that appears, you will see a list of the last three commits. Change the
pickkeyword toeditfor the commit you want to modify, then save and exit the editor. -
Changing the commit timestamp: Use the following command to update the timestamp:
shellGIT_COMMITTER_DATE="Wed Feb 16 14:00 2022 +0100" git commit --amend --no-edit --date "Wed Feb 16 14:00 2022 +0100"Adjust the date as needed.
-
Completing the modification and continuing rebase: After making changes, continue the rebase process with:
shellgit rebase --continueIf multiple commits require editing, repeat steps 2 to 4.
-
Resolving potential conflicts: Conflicts may arise during rebase. If so, Git will pause until you resolve them. After resolving conflicts, mark them as fixed with
git add, then proceed with the rebase. -
Forcing push to the remote repository: Since the commit history has been modified, force push the changes using:
shellgit push --forceNote that this may disrupt other collaborators' work.
This is a powerful yet risky operation as it alters the repository history. Before proceeding, ensure you understand the potential consequences and communicate with your team. In specific scenarios, such as issues caused by incorrect commit timestamps, this method is highly useful.