Quite simple:
If you hold the shares at the end of the day before they go ex dividend, you receive the dividend. It's immaterial whether you bought them on that day or many months before.
If you buy them on or after ex-div day, you won't receive a cent.