Committing to a Git repository using custom dates

git 0 Comments

Occasionally I want to create a Git repository for some ancient piece of code in my SVN repository. As I haven't had any luck in exporting parts of my giant mono repository, I tend to just grab the lowest folder, initialise a new git repository and commit. But if I do that, then everything is tagged with the current timestamp, which is definitely not what I want for code that I haven't touched in years.

Fortunately Git allows you to force the dates when you commit. Not so fortunately, the way of doing it isn't obvious (not to mention Git has two different date systems) and so whenever I want to do it, I've forgotten the specifics and need to look it up. This post serves as a reminder for myself rather than a more informative post for general use.

Before committing, set the GIT_COMMITTER_DATE and GIT_AUTHOR_DATE environment variables with the timestamp you want to use. I usually use ISO 8601 format but you can also use RFC 2822.

set GIT_COMMITTER_DATE="2011-12-02T23:37:52"

set GIT_AUTHOR_DATE="2011-12-02T23:37:52"

If using Linux or Git Bash on Windows, use export instead of set

Defining the environment variables that our commit will use
Defining the environment variables that our commit will use

Now I can git commit and it will use the custom dates provided by the environment variables. If I do git log I can see it shows the correct date. Or one of them anyway.

The output of `git-log`, showing that at least one date date was used
The output of `git-log`, showing that at least one date date was used

Alternatively, to be sure I've got the pair of dates correct, I can use custom formatting to print both dates

git log --pretty="Author date: %ad, Committer date: %cd"

The output of `git-log` with a custom format string, showing that both the committer and author dates were used
The output of `git-log` with a custom format string, showing that both the committer and author dates were used

One word of caution - as these are environment variables, if you make another commit from the same session, it will re-use the variables which may not be what you wanted.