Most scholars believe that Shakespeare wrote A Midsummer Night's Dream as a light entertainment to accompany a marriage celebration; and while the identity of the historical couple for whom it was meant has never been conclusively established, there is good textual and background evidence available to support this claim. At the same time, unlike the vast majority of his works (including all of his comedies), in concocting this story Shakespeare did not rely directly upon existing plays, narrative poetry, historical chronicles or any other primary source materials, making it a truly original piece. Most critics agree that if a youthful Shakespeare was not at his best in this play, he certainly enjoyed himself in writing it.
Most scholars think the play was written in 1595 or 1596, to answer the second part of your question.
He had come up with the idea for the book "A Midsummer Night's Dream" when he had witnessed an aristocratic wedding, with Queen Elizabeth I as the audience. To answer the second question, the play was written around the years of 1595-1596, when he was around the ages of 31-32 years old, most probably the same period as Romeo and Juliet, another tragic love story.