How to display local time to users in browser?

In 7 years web programming career, I never met this problem before. In a recent project we needed to show browsers local time on the page. Few folks have solutions to do this server side but none of them work reliably. Why?
  • Browsers don't send any timezone information
  • You can send offset in headers / parameters but its only reliable for dynamic requests
After trying a failing multiple times, I resorted to a browser-based JavaScript solution. This works great!
  1. Convert all the server side timestamps to UTC. This makes server side code life way easier!
  2. Send the dates to browser in iso8601 format which JavaScript can parse easily.
  3. I used very good jQuery library (Localtime)  to convert iso8601 formatted dates to format required by application.
You can also tag your date spans with a special class. This way you can convert all timestamps to different formats unobtrusively. Very simple and elegant solution.

Published October 15 2011

blog comments powered by Disqus