There's no definite answer to this one, and it's a question that scholars love to argue about. The scene in question is the gravediggers scene, Act 5, Scene 1. Hamlet asks the gravedigger how long he's been digging graves, and the gravedigger responds that he came to the job "the very day that young Hamlet was born".
A few lines later, he confirms that he has been "sexton here,
man and boy, thirty years". Hamlet then, if we believe this evidence, must be thirty years old.
But doesn't Hamlet come back from university to his father's funeral - why would a thirty year old be studying at university? Surely Hamlet is a young man? It is perfectly plausible to suggest that the gravedigger might mean 'thirty years' in a very general way, rather than as a specific detail, in order to support such an argument.
Some critics think that Hamlet was originally written as a younger man, but the popularity of the play and the ageing of Richard Burbage (who originally played the role) forced Shakespeare to rewrite it to accommodate his leading man.
Hamlet's age is debateable. When Hamlet is talking with the gravediggers in Act 5, sc. 1, the first gravedigger says Yorick has been dead for 23 years. Yorick was a court jester when Hamlet was a boy so that would indicate that Hamlet is about 30. At the beginning of the play however, we are told he had been away at college when his father died and that was just about two months ago. Most college students are under the age of 30. The question of time passage in the play is vague, too, remember. When they are watching the play within the play, Hamlet tells Ophelia that his father's been dead "...within these two hours," and Ophelia tells him it's been four months since his father died (Act 3, sc. 2). We get the feeling as we read the play that things happen at a steady pace, but that's not necessarily so, for example, it would have taken some time for news of Polonius's death to reach Laertes and then for him to get back to Denmark. I explain all that to suggest that maybe when Hamlet leaves Denmark and is taken aboard the pirate ship, we don't really know how long he was gone. Years may have passed from the beginning of the play to the scene in the graveyard which would put Hamlet at about 30. Also, we can't be certain that the lines were all written correctly from memory and that is how most of the lines were recorded.