You can buy them almost a year before, or upto just a few minutes before flight time. Price will vary dramatically, though.
The further in advance you buy, generally you get better savings. We have bought tickets only a day or two in advance though. But you will more likely be searched more if you buy a day or two ahead. You will get what they call "red-flagged" It happened to us.
Most of the time--the further in advance that you buy the tickets, the lower a price you will get compared to someone who waits a week or two to go to the same travel destination as you. I bought tickets almost a year in advance for trip to Brazil and only paid about $650 whereas if I waited closer to destination time--over $1000.
You can buy an ticket whenever you want BUT to get the best ticket price, try to book your flight a month in advance. But do remember this sometimes if you buy a ticket at the last minute, you'll get a deal because they are trying to fill a flight up, so they will go really low on airfare! Hunting and research helps!