The 15-year-old victim found it extremely distressing "and understandably so", Judge Emma Smith told a man who did an indecent act in the Dunedin Public Library.
The victim was in the teen area on the second floor. She was in what should have been a safe place "and you violated that", the judge said.
Adam Charlett, 23, of Dunedin, had been convicted of doing an indecent act.
He had pleaded guilty.
The police summary said the victim was lying on a couch in the teen area watching a movie on her phone with her headphones in her ears, about 3.10pm.
She was not known to Charlett.
Charlett entered the teen area and stood behind a bookshelf.
While looking at the victim, Charlett put his right hand down his shorts.
After about three minutes, he stepped from behind the bookshelf towards the victim, and exposed himself while leaning over her, breathing in her ear.
The victim jumped to her feet and Charlett covered up. He spoke to her for a short time.
She asked him to leave, which he did soon after.
When the victim reported the matter to library staff they viewed CCTV footage and saw what Charlett had done.
In explanation, Charlett said he had been "on datura" and did it as a dare.
Counsel Debbie Ericsson said Charlett's past two months in custody equated to a four-month sentence. He had been on medication in custody and had gained insight into his issues.
Charlett had previous offending "but nothing of this type".
Judge Smith noted Charlett was on release conditions at the time. He had mental health difficulties and he said he was particularly sorry for the offending.
Charlett was sentenced to four months' jail, court costs $130.
The judge imposed no release conditions, Charlett already being subject to them until the end of the year.