Djokovic, a 24-time Grand Slam winner, is playing in the ATP 250 tournament in Switzerland for the first time as preparation for the French Open and recorded a 6-3 6-3 victory.
It made him only the third player – after Jimmy Connors and Roger Federer – to win 1,100 matches on the ATP Tour.
At the end of the match, the crowd sang ‘happy birthday’ to Djokovic and he was also presented with a chocolate birthday cake by tournament officials.
“My birthday wouldn’t have been the same if I had not won the match,” said Djokovic.
“I’m very grateful for all the people that came out to support me and thank you for the birthday song, that was very special for me.”
The world number one is yet to reach a final in 2024 and will next face either Canada’s Denis Shapovalov or Dutch sixth seed Tallon Griekspoor.
In the opening round, Hanfmann won 7-5 6-2 against Britain’s Andy Murray, who had been playing his first ATP Tour-level match since rupturing ankle ligaments at the Miami Open in March.
But the 32-year-old German, 85th in the world, had his serve broken by Djokovic in the sixth game and then failed to convert two break-point opportunities soon after.
With Djokovic serving for the set at 5-3, Hanfmann missed four break points, before the match was paused at deuce in the ninth game – which was the start of a rain delay of more than an hour.
When play resumed, Djokovic quickly sealed the set, although Hanfmann then broke his serve at the start of the second on his way to a 3-0 lead.
He had a chance to move a double break ahead, but could not take it, with Djokovic getting the match back on serve in the next game, aided by a fine sliced drop shot that Hanfmann was unable to gather.
Djokovic, helped by two excellent cross-court winners in the ninth game, won six games in a row to seal the victory.
Earlier this month, he had lost 6-2 6-3 in just 67 minutes to Alejandro Tabilo in the third round of the Italian Open, although the Serb said he had been hampered by the after-effects of accidentally being hit on the head by a water bottle two days earlier.
The French Open begins on Sunday, with Djokovic looking to retain his title and win the competition for a fourth time.