乐闻世界logo
搜索文章和话题

How can one change the timestamp of an old commit in Git?

1个答案

1

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:

  1. Using git rebase command: To change the timestamp of a specific commit, use the git rebase command in interactive mode. For example, to modify one of the last three commits, execute:

    shell
    git rebase -i HEAD~3
  2. Selecting the commit to edit: In the editor that appears, you will see a list of the last three commits. Change the pick keyword to edit for the commit you want to modify, then save and exit the editor.

  3. Changing the commit timestamp: Use the following command to update the timestamp:

    shell
    GIT_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.

  4. Completing the modification and continuing rebase: After making changes, continue the rebase process with:

    shell
    git rebase --continue

    If multiple commits require editing, repeat steps 2 to 4.

  5. 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.

  6. Forcing push to the remote repository: Since the commit history has been modified, force push the changes using:

    shell
    git push --force

    Note 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.

2024年6月29日 12:07 回复

你的答案