I always start the day thinking I'll easily get this done by the end of the day and set what looks like a realistic target.So why do I never hit it? The task always ends up taking 3x longer due to unforeseen bugs, last minute changes etc.Is it just me?  I don't seem to be getting any better predicting what can be done in a day.
Why is it you never get as much done as you'd planned?
productivity;self improvement
Because you were never taught how to plan.Planning is a skill, just like coding or writing. But somehow it is left out of nearly every curriculum. It needs to be learned and practiced, and your estimates of your own capabilities need to be continuously updated. This is why work practices like Agile emphasize measuring your past actual work and comparing it to your estimates, so that you can improve your planning abilities.As others have said, you need to account not only for the task, but for all its predecessors, attendant tasks (e.g., learning how to do X), and you need to be cognizant of your own internal mental biases that will prevent you from correctly accounting for the way you actually do work.Train on it, and who knows, you might get better.