Do you know how to change the date of an existing commit?
Last updated by Jeoffrey Fischer [SSW] 6 months ago.See historyUpdating commit information can be essential for maintaining accurate project history or correcting errors. Whether you need to change a commit date for clarity, compliance, or other reasons, you have a couple of methods at your disposal.
This rule outlines how to change the date of an existing commit using both a manual CLI approach and an automated script.
Method 1 – Use CLI
-
Checkout to the branch containing the commit
git checkout -b {{ BRANCH NAME }} origin/{{ BRANCH NAME }}
-
Run git log to get the last commit hash
git log
-
Do an interactive rebase for the parent of the last commit
git rebase -i {{ COMMIT HASH }}^
-
This opens vi editor:
- Press "I" key to enter interactive mode,
- Change "pick" to "edit",
- Press "escape" to exit interactive mode,
- Type ":wq" to save and exit
-
Change the commit date
GIT_COMMITTER_DATE="{{ NEW DATE IN 'YYYY-MM-DD HH:MM:SS' FORMAT }}" GIT_AUTHOR_DATE="{{ NEW DATE IN 'YYYY-MM-DD HH:MM:SS' FORMAT }}" git commit --amend --no-edit
-
Finish the rebase
git rebase --continue
-
Force push to origin
git push origin {{ BRANCH NAME }} --force
Method 2 (recommended) – Use a script
If the date change is to be applied on several branches, it is preferable to automate the process with a script.
BRANCH=$1
DATE=$2
if [ -z "$BRANCH" ] || [ -z "$DATE" ]; then
echo "Usage: $0 {{ BRANCH NAME }} {{ NEW DATE IN 'YYYY-MM-DD HH:MM:SS' FORMAT }}"
exit 1
fi
git checkout -b "$BRANCH" "origin/$BRANCH"
LAST_COMMIT_HASH=$(git log -n 1 --pretty=format:"%H")
git rebase -i "$LAST_COMMIT_HASH^"
GIT_COMMITTER_DATE="$DATE" GIT_AUTHOR_DATE="$DATE" git commit --amend --no-edit
git rebase --continue
git push origin "$BRANCH" --force
git checkout main
The script can be actioned with the following command:
./change_history.sh "{{ LOCAL PATH }}" "{{ NEW DATE IN 'YYYY-MM-DD HH:MM:SS' FORMAT }}"