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

后端 未结 21 2411
慢半拍i
慢半拍i 2020-11-22 08:36

The answers to How to modify existing, unpushed commits? describe a way to amend previous commit messages that haven\'t yet been pushed upstream. The new messages inherit t

相关标签:
21条回答
  • 2020-11-22 09:03

    Set the date of the last commit to the current date

    GIT_COMMITTER_DATE="$(date)" git commit --amend --no-edit --date "$(date)"
    

    Set the date of the last commit to an arbitrary date

    GIT_COMMITTER_DATE="Mon 20 Aug 2018 20:19:19 BST" git commit --amend --no-edit --date "Mon 20 Aug 2018 20:19:19 BST"
    

    Set the date of an arbitrary commit to an arbitrary or current date

    Rebase to before said commit and stop for amendment:

    1. git rebase <commit-hash>^ -i
    2. Replace pick with e (edit) on the line with that commit (the first one)
    3. quit the editor (ESC followed by :wq in VIM)
    4. Either:
    • GIT_COMMITTER_DATE="$(date)" git commit --amend --no-edit --date "$(date)"
    • GIT_COMMITTER_DATE="Mon 20 Aug 2018 20:19:19 BST" git commit --amend --no-edit --date "Mon 20 Aug 2018 20:19:19 BST"

    Source: https://codewithhugo.com/change-the-date-of-a-git-commit/

    0 讨论(0)
  • 2020-11-22 09:05

    After reading all the answers I came up with a more succinct and convenient way of editing the date of multiple commits at once without the need of rebasing interactively:

    git rebase HEAD~4 --exec "git commit --amend --no-edit --date 'now'"
    

    It changes both the committer and author dates.

    0 讨论(0)
  • 2020-11-22 09:06

    Here is a convenient alias that changes both commit and author times of the last commit to a time accepted by date --date:

    [alias]
        cd = "!d=\"$(date -d \"$1\")\" && shift && GIT_COMMITTER_DATE=\"$d\" \
                git commit --amend --date \"$d\""
    

    Usage: git cd <date_arg>

    Examples:

    git cd now  # update the last commit time to current time
    git cd '1 hour ago'  # set time to 1 hour ago
    

    Edit: Here is a more-automated version which checks that the index is clean (no uncommitted changes) and reuses the last commit message, or fails otherwise (fool-proof):

    [alias]
        cd = "!d=\"$(date -d \"$1\")\" && shift && \
            git diff-index --cached --quiet HEAD --ignore-submodules -- && \
            GIT_COMMITTER_DATE=\"$d\" git commit --amend -C HEAD --date \"$d\"" \
            || echo >&2 "error: date change failed: index not clean!"
    
    0 讨论(0)
提交回复
热议问题