28 November 2021

Sometimes could be usefull to change a date of a git commit, weekend refactoring ;)

Note: all example below could be execute in a container:

docker run -it  ubuntu /bin/bash
apt update && apt install git
git config --global user.email "you@example.com"
git config --global user.name "Your Name"

Change latest commit to current date

  1. Create repository

    cd /tmp && mkdir change-latest-commit && cd change-latest-commit && git init
    
  2. First commit

    echo "Test" > text.txt && git add . && git commit -m "Initial commit"
    
  3. Git History show the date

    # git show --pretty=fuller
    commit 1e11854790cbffe9467a1b41a4f0fc1b872d4eb2 (HEAD -> master)
    Author:     Your Name <you@example.com>
    AuthorDate: Sun Nov 28 06:14:52 2021 +0000
    Commit:     Your Name <you@example.com>
    CommitDate: Sun Nov 28 06:14:52 2021 +0000
    
        Initial commit
    
    diff --git a/text.txt b/text.txt
    new file mode 100644
    index 0000000..345e6ae
    --- /dev/null
    +++ b/text.txt
    @@ -0,0 +1 @@
    +Test
    
  4. Change dte of the commit
    Note: the parameter --date change git author date so in order to change git commit date and author date consistently it
    is required to set GIT_COMMITTER_DATE and use of --date.

    (export GIT_COMMITTER_DATE="Thu, 07 Apr 2005 22:13:13 +0200" && git commit --amend --no-edit --date "$GIT_COMMITTER_DATE")
    
  5. Show in git log that a commit changed date

    # git show --pretty=fuller
    commit b1623b40aa9cf1acb80dddc7714b130983d291fc (HEAD -> master)
    Author:     Your Name <you@example.com>
    AuthorDate: Thu Apr 7 22:13:13 2005 +0200
    Commit:     Your Name <you@example.com>
    CommitDate: Thu Apr 7 22:13:13 2005 +0200
    
        Initial commit
    
    diff --git a/text.txt b/text.txt
    new file mode 100644
    index 0000000..345e6ae
    --- /dev/null
    +++ b/text.txt
    @@ -0,0 +1 @@
    +Test
    

References