The short answer
He had the theory by the autumn of 1838 and published it in November 1859. Fear of the Church, of scandal and of his wife's feelings was real. But the deeper reason is that natural selection cannot be seen, so it could not be shown, only argued, and he spent the years assembling the argument.
What he had, and when
July 1837: a notebook on the transmutation of species, with a branching tree and I think. September 1838: Malthus, and the mechanism. 1842: thirty-five pages in pencil. 1844: a 230-page essay, and a letter to Emma asking her to spend four hundred pounds publishing it if he died.
What he did with the years
He had learned, painfully, what happens to a man who argues only from the alternatives he happens to have thought of: his 1839 theory of the parallel roads of Glen Roy was wrong, and he called it a great failure, and I am ashamed of it.
So he built evidence for a process no one would ever witness. Eight years on barnacles. Three years breeding pigeons with London fanciers, because breeders were doing on purpose and in public what nature does slowly. Seeds soaked in brine to see if they could float to islands. Thousands of letters to breeders, gardeners and naturalists.
What ended it
On 18 June 1858 an essay arrived from Alfred Russel Wallace with the same idea. Darwin had been overtaken while carrying something he had carried for twenty-one years. He wrote the Origin, which he called an abstract, in little more than a year.