0

I want to display 3 clocks from 3 different time zones using JavaScript. I browsed around the web searching for a simple solution but all I found was long scripts and .js extensions, all those to complete a simple task.

Is there an easy way to do this? do I really have to add an additional JS file to complete this task?

Thanks in advance to the helpers!

natiz
  • 563
  • 1
  • 15
  • 29
  • Handling times in JS is a PITA... which is why things like [MomentJS](http://momentjs.com/) exist. – Ben Lesh Feb 19 '13 at 19:29
  • possible duplicate of [How to get Time of specific timezone using javascript?](http://stackoverflow.com/questions/8207655/how-to-get-time-of-specific-timezone-using-javascript) – Ben Lesh Feb 19 '13 at 19:32

1 Answers1

3

Is there an easy way to do this?

Yes.

do I really have to add an additional JS file to complete this task?

No. However, time handling in JS is difficult, since it has no really cross-browser-safe date/timestring parsing and formatting methods. It can be helpful to use a library for that, however that won't be necessary for your clock.

// all three clocks represent current time
var clock1 = new Date(); // current moment
var clock2 = new Date();
var clock3 = new Date();

// for outputting, adjust them
// leave clock1 in UTC
clock2.setHours(clock2.getHours() + 3); // UTC+3
clock3.setHours(clock3.getHours() - 5); // UTC-5

// now for display, use these values:
clock1.getUTCHours();
clock1.getUTCMinutes();
clock1.getUTCSeconds();

clock2.getUTCHours();
clock2.getUTCMinutes();
clock2.getUTCSeconds();

clock3.getUTCHours();
clock3.getUTCMinutes();
clock3.getUTCSeconds();
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thank you for your solution, Bergi. Just a quick question - does this also take into account the DST timings? meaning if the UTC-5 clock should be actually UTC-4 due to daylight savings, will it make the adjustments? – natiz Feb 19 '13 at 22:06
  • No. UTC-5 will stay UTC-5, you will need to determine yourself whether the timezone you want to display currently has DST (and you need to display UTC-4). Or let an [existing library](https://github.com/mde/timezone-js) do it for you, since DST calculation is complex. – Bergi Feb 19 '13 at 23:10