Table of contents

  1. 1. Moment.js
  2. 2. Convert to milliseconds
    1. 2.1. Using a predefined UTC offset
    2. 2.2. Using UTC offset detection
    3. 2.3. Using a predefined time zone
    4. 2.4. Using time zone detection

Learn how to get the milliseconds of a specified date in your desired timezone.

Moment.js

Moment.js is a great library if you want to work with dates and times in TypeScript. It is very handy for creating interchange representations like ISO 8601 strings, taking your current timezone into account.

Convert to milliseconds

Let’s say you live in Berlin (Germany), and you want to represent June, 26th of 2019 at midnight in milliseconds with Central European Summer Time (GMT+2). Using Moment.js v2.24 you have at least the following possibilities to do that:

Using a predefined UTC offset

defined-utc-offset.ts
1
2
3
4
5
import moment from 'moment';

const unixTimestamp = moment('2019-06-26T00:00:00.000+02:00').valueOf();

console.log('unixTimestamp', unixTimestamp); // 1561500000000

Using UTC offset detection

detected-utc-offset.ts
1
2
3
4
5
6
7
import moment from 'moment';

const utcOffsetInMinutes = new Date().getTimezoneOffset(); // -120 (2 hours)
const utcOffsetInMillis = utcOffsetInMinutes * 60000;
const unixTimestamp = moment('2019-06-26T00:00:00.000Z').valueOf() + utcOffsetInMillis;

console.log('unixTimestamp', unixTimestamp); // 1561500000000

Using a predefined time zone

defined-zone-info.ts
1
2
3
4
5
6
7
import moment from 'moment';
import 'moment-timezone';

const zoneInfo = 'Europe/Berlin';
const unixTimestamp = moment.tz('2019-06-26 00:00:00', zoneInfo).valueOf();

console.log('unixTimestamp', unixTimestamp); // 1561500000000

Using time zone detection

detected-zone-info.ts
1
2
3
4
5
6
7
import moment from 'moment';
import 'moment-timezone';

const zoneInfo = moment.tz.guess();
const unixTimestamp = moment.tz('2019-06-26 00:00:00', zoneInfo).valueOf();

console.log('unixTimestamp', unixTimestamp); // 1561500000000

Pro Tip: You can get date and time expressed according to ISO 8601 in TypeScript from the current date when calling:

1
new Date().toISOString(); // "2019-07-03T13:12:18.784Z"

Note that the above string will always be normalized to UTC time (Z). To prevent UTC conversion you have to call:

1
new Date().toISOString(true); // "2019-07-03T15:12:18.784+02:00"