How do you end a social interaction in a way that doesn't offend/hurt the other person?

I struggle sometimes because I don't want to appear rude, but then end up staying in the interaction a bit longer than I want. I was on a first date with this girl the other day that went on for 2 hours, about an hour longer than I would've liked, but wasn't really sure how to end it.

Then yesterday I was at a social gathering, talking to this person who at some point was just rambling and I was like okay I got to get out of this. I found an opportunity to make a joke with a sort of closure vibe, and gently walked away to grab some food at the same time. Seemed like that worked well.