Glucose in the blood binds with and damages red blood cells. There's a category of haemoglobin (A) that's around 90% of all haemoglobin and comparatively easy to count, and the test can count how many of those red blood cells have been glycated. HbA1c is the major glycated component, and the results correlate fairly well with average blood glucose.
Red blood cells live about 90-120 days maximum, so any RBCs from before then will probably have already been cleared up. The test is skewed towards the last month - 50% of the value reflects the 30 days prior to the test, and only 10% the initial 30 days of red blood cell life.
It's not spot on, there is some variation between tests, and around test accuracy (I've had a completely off the wall result recently, which was proved very wrong when checked against a full lab test), but these are usually relatively small amounts. It's why they repeat the HbA1c for T2 diagnosis if the initial result is close to 48. There's also a number of other conditions - iron deficiency, pregnancy, red cell disorders etc, that can affect the test.
So, not a perfect and totally accurate test, but good enough for most purposes.
Source for the above: Bilous and Donnelly, Handbook of Diabetes.
[edited for clarity]