How to Convert Date to UTC in Typescript?

In this Typescript tutorial, I will explain how to convert date to UTC in Typescript using various methods.

To convert a date to UTC in TypeScript, you can use the JavaScript Date object’s toISOString() method for quick conversion. Alternatively, for more control, manually construct a UTC date using Date.UTC(). Libraries like moment.js or date-fns are also excellent for handling more complex date conversions.

Convert Date to UTC in Typescript using the Date object

The easiest way to convert date to UTC format in Typescript is using the Date object. Here is a complete code:

function convertToUTC(date: Date): string {
    return date.toISOString();
}

const localDate = new Date();
const utcDate = convertToUTC(localDate);
console.log(utcDate);

This function takes a Date object and converts it to the ISO string format, which is inherently in UTC.

You can see the output in the screenshot below:

typescript convert date to utc

Convert Date to UTC in Typescript using Manual Conversion

You can also convert the date to UTC in Typescript using manual conversion. Here is the complete code:

function manualConvertToUTC(date: Date): Date {
    return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
}

const localDate = new Date();
const utcDate = manualConvertToUTC(localDate);
console.log(utcDate);

You can see the below screenshot.

Convert Date to UTC in Typescript

Typescript convert date to UTC using various libraries

For more complex applications, you might consider using a library like moment.js or date-fns to convert date to UTC in Typescript.

Using moment.js:

You can use the moment.js library to convert a date to UTC in Typescript. Here is the complete code:

import moment from 'moment';

function convertUsingMoment(date: Date): string {
    return moment(date).utc().format();
}

const localDate = new Date();
const utcDate = convertUsingMoment(localDate);
console.log(utcDate);

Using date-fns:

Here is the complete code to convert a date to UTC in Typescript using date-fns library. Here is the complete code:

import { formatUTC } from 'date-fns';

const localDate = new Date();
const utcDate = formatUTC(localDate, 'yyyy-MM-dd HH:mm:ssX');
console.log(utcDate);

Conclusion

Various methods can be used to convert dates to UTC in Typescript, such as using the Date object with third-party libraries like moment.js, date-fns, etc.

You may also like:

>