Only investors whose names are in the company's records on that date receive the benefit. Because trades take a day to settle, the exchange sets an ex-date shortly before it: shares bought on or after the ex-date do not get the dividend.
To receive a dividend, you need to hold the shares before the ex-date. The company announces both dates in advance.
Related terms: Dividend, Bonus shares, Demat account.