David Torres David Torres - 1 year ago 84
Node.js Question

How to tell JavaScript Date where to take TimezoneOffset from?

I am using

new Date(<date-string>)
and then
to pass date strings to milliseconds from 1970.

The problem is that the date strings does not contain the timezone on them. They are British, so the timezone will be GMT or GMT+1 depending on the date...

When I use this technique in the front-end (Chrome), or in the back-end (Node.js). The time zone taken is the British one (GMT or GMT+1 depending on the date). I assume that is taken from the OS.

However, when using a Node.js server which I have been told is configured to be in UTC... the timezone is always going to be GMT, leading to errors during the British Summer Time.

Is there any way to tell
to take the timezone from the OS without changing the server configuration?


var aDate = new Date('2016-06-23 10:15:0');
var timestamp = aDate.getTime();

Just in case my explanation is not clear:

// Executed on 28-06-2016

// In the browser (in London)
new Date().getTimezoneOffset(); // -60
new Date('28-06-2016 11:11:11').getTimezoneOffset(); // -60
new Date('28-01-2016 11:11:11').getTimezoneOffset(); // 0

// In the Node.js server I am forced to use, which is configured to use UTC
new Date().getTimezoneOffset(); // 0
new Date('28-06-2016 11:11:11').getTimezoneOffset(); // 0
new Date('28-01-2016 11:11:11').getTimezoneOffset(); // 0

// Ideally, I would like to have the output I get in the browser when I run the code in the UTC Node.js server

Answer Source

I recommend using Moment Timezone for this, since this would be needlessly complicated to implement without a library. To get UTC in milliseconds from a given date in a given timezone, you can do this:

const moment = require('moment-timezone');

function londonTimeToUTC(dateString) {
  return moment.tz(dateString, 'DD-MM-YYYY HH:mm:ss', 'Europe/London').valueOf();

console.log(londonTimeToUTC('28-06-2016 11:11:11')); // 1467108671000
console.log(londonTimeToUTC('28-01-2016 11:11:11')); // 1453979471000

The second argument passed to moment.tz() is a format string, which is necessary if the date string is not in ISO format. The third argument is any valid timezone identifier.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download