Thomas Jefferson started writing the declaration of independence in June 1776. Independence was declared on July 2. The declaration was signed on August 2, and delivered to the Brits in November.
After the first draft of the declaration was submitted on July 2, Congress worked on edits and tweaks—probably debating the deep meaning of its punctuation as we still are, 238 years later—until they settled on a final version on July 4.
The date was included in the draft which was then signed in August.