Gandalf has everything to do with it. When the trolls are arguing over whether/how to kill Bilbo and the dwarves, Gandalf chimes in (out-of-sight), sounding like one of the other trolls. He does this repeatedly, because he knows the trolls are not that intelligent and if he can keep them arguing, the sun will come up and his companions will be safe. So Gandalf goads the trolls on by making his voice sound like each of them in turn, fostering the argument about how to eat Bilbo and the dwarves.
And then the sun comes up. I don't recall anywhere that Tolkien explains why this is so, but from the general mythos of trolls, we know they are associated with caves and dark places. In light of that, it makes sense that the sun would destroy them in some way.* And while the sun is what actually turns them to stone, Gandalf's deception is what causes the trolls to remain where the daylight can reach them, instead of hiding before dawn.
*I don't recall if Sauron used trolls in battle in the books; it's been a while since I've read them. That being said, there may be many varieties of troll, and Sauron may have selectively bred them to be immune to sunlight, but Sauron also used smoke and darkness to aid his orcs and trolls