Companies can set a date whereby shares sold before that time will lose their dividend. If you sell shares after this date, you'll still receive the dividend.