The story
According to some, the expression originally literally referred to greeting someone with the obsolete greeting "good time of day", or other greeting appropriate to the time of day (e.g., good morning, good afternoon, good evening), and only later acquired an association with telling someone the time, along with its idiomatic sense.
Etymology from Wiktionary, CC BY-SA 4.0.