ยท hands on

Convert to milliseconds

Learn how to get the milliseconds of a specific date in your desired timezone using Moment.js. You can use a predefined UTC offset or detect the UTC offset. You can also use a predefined time zone or detect the time zone.

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

Contents

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
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
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
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
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:

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:

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