There are two 'dates' relevant to your question: Ex-Dividend and Record. To find out these dates for a specific security visit Dividend.Com.
You have to purchase the security prior to the Ex-Dividend date, hold it at least until the Record Date. After the Record Date you can sell the security and still receive the dividend for that quarter.
---- edit - - - -
I was wrong. If you sell the security after the Ex-div date but before the date of record you still get the dividend.
http://www.investopedia.com/articles/02/110802.asp