It's not easy getting the age for a star. Using special instruments, we can find dark lines in the spectrum that correspond to the elements in a star. The element lithium can be used to get an age for a star because the amount of lithium in a star decreases with time. This is because it gets converted to other elements by nuclear reactions. The second method is to find the age of a cluster, or group, of stars.
Many stars form together in clusters, so they all have the same age.
We know from our calculations that very big, massive stars burn up their nuclear fuel very fast and have short lifetimes, while smaller stars use up their fuel much more slowly and can continue giving off light for much longer. Then we can figure out that all the stars in the cluster must be the same age as the age of the stars that just recently used up their nuclear fuels. For instance, if all the stars that are greater than three times as massive as our sun have run out of nuclear fuel and have become red giants, then we know that all the stars in the cluster are 500 million years old. That is because the sun is so much closer than the other stars. But if you could line up a bunch of stars, including our sun, all at the same distance, you would see that some stars are brighter and some are fainter than our sun.