0

I try to implement world-clock with node.js and timezone-js

For weird reason, I could not find any example to make it work, like hello-world program.

So here's my try:

var timezoneJS = require('timezone-js');

timezoneJS.timezone.zoneFileBasePath = './tz';
timezoneJS.timezone.init();

var getTime = function(timezone)
{
  var UTC = new timezoneJS.Date(new Date(), 'Etc/UTC'); //for unknown reason this works only for Etc/UTC

  var YYYY = UTC.getFullYear();
  var MM = UTC.getMonth() + 1;
  var DD = UTC.getDate();
  var hh = UTC.getHours();
  var mm = UTC.getMinutes();
  var ss = UTC.getSeconds();

  var dt = new timezoneJS.Date(YYYY, MM, DD, hh, mm, ss, timezone);

  var date = dt.getFullYear() + '/' + (dt.getMonth() + 1) + '/' + dt.getDate();
  var time = ('0' + dt.getHours()).slice(-2) + ':' + ('0' + dt.getMinutes()).slice(-2) + ':' + ('0' + dt.getSeconds()).slice(-2);

  var datetime = date + ' ' + time;
  return datetime;
};

log(getTime('Europe/London'));
log(getTime('America/New_York'));

and the result goes:

$ node app
'2014/7/16 14:30:40'
'2014/7/16 14:30:40'

same for London and NY. How does this happen? and let me know how to fix.

Thanks.

  • Mon Jun 16 2014 16:28:24 *GMT+0100* (Romance Standard Time), where is the GTM in your dates? – jmingov Jun 16 '14 at 15:28
  • Sorry, I don't understand your query. Problem solved by the following answer. thanks! –  Jun 16 '14 at 17:13

1 Answers1

0

You should be able to omit the first part of the function and simply do this:

var dt = new timezoneJS.Date(Date.now, timezone);

The reason it isn't working as you've written it, is that you're initializing the date to the same year/month/day/hour/minute/second in two different time zones. In other words - they're not representing the current time - they've been erroneously shifted by the UTC offset.

You might also consider moment-timezone, or one of the other libraries listed here.

Community
  • 1
  • 1
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • Great answer. I once knew moment.js but have forgotten. Those set looks really promising. Thanks a lot, Matt. –  Jun 16 '14 at 16:51