You can apply once you meet the core requirements, and residence time is only one of them. The others are a stable attachment to the labour market, self-sufficiency, and passes in the Danish language tests and the citizenship test (indfødsretsprøven). The minimum period of residence is either 4 or 8 years depending on your situation.
So the timing is not simply a matter of counting years. It is a matter of whether every requirement is satisfied on the day you apply. Applying at the earliest possible point, after 4 years, means the basic and the supplementary conditions all have to be in place by then.
The rules here are technical and they change, which is why it is worth having the case checked before the application goes in. A refusal you could have foreseen costs time you do not get back.