Convert a Date to UTC in JavaScript or Node.js

Working with dates in an application requires you to think of time zones. Users are going to access your application from different time zones. They expect displayed dates to either match their personal timezone or to contain the timezone information, a la UTC+02:00.

A common approach to handling dates in an application is to store them in the UTC timezone. The UTC storage allows you to convert dates and times to your needs by adding or subtracting the offset hours for a user.

This tutorial shows you how to convert a date instance to UTC in JavaScript.

Node.js Series Overview

  1. String Replace All Appearances
  2. Remove All Whitespace From a String in JavaScript
  3. Generate a Random ID or String in Node.js or JavaScript
  4. Remove Extra Spaces From a String in JavaScript or Node.js
  5. Remove Numbers From a String in JavaScript or Node.js
  6. Get the Part Before a Character in a String in JavaScript or Node.js
  7. Get the Part After a Character in a String in JavaScript or Node.js
  8. How to Check if a Value is a String in JavaScript or Node.js
  9. Check If a String Includes All Strings in JavaScript/Node.js/TypeScript
  10. Check if a Value is a String in JavaScript and Node.js
  11. Limit and Truncate a String to a Given Length in JavaScript and Node.js
  12. Split a String into a List of Characters in JavaScript and Node.js
  13. How to Generage a UUID in Node.js
  14. Reverse a String in JavaScript or Node.js
  15. Split a String into a List of Lines in JavaScript or Node.js
  16. Split a String into a List of Words in JavaScript or Node.js
  17. Detect if a String is in camelCase Format in Javascript or Node.js
  18. Check If a String Is in Lowercase in JavaScript or Node.js
  19. Check If a String is in Uppercase in JavaScript or Node.js
  20. Get the Part After First Occurrence in a String in JavaScript or Node.js
  21. Get the Part Before First Occurrence in a String in JavaScript or Node.js
  22. Get the Part Before Last Occurrence in a String in JavaScript or Node.js
  23. Get the Part After Last Occurrence in a String in JavaScript or Node.js
  24. How to Count Words in a File
  25. How to Shuffle the Characters of a String in JavaScript or Node.js
  26. Append Characters or Words to a String in JavaScript or Node.js
  27. Check if a String is Empty in JavaScript or Node.js
  28. Ensure a String Ends with a Given Character in JavaScript or Node.js
  29. Left-Trim Characters Off a String in JavaScript or Node.js
  30. Right-Trim Characters Off a String in JavaScript or Node.js
  31. Lowercase the First Character of a String in JavaScript or Node.js
  32. Uppercase the First Character of a String in JavaScript or Node.js
  33. Prepend Characters or Words to a String in JavaScript or Node.js
  34. Check if a String is a Number
  35. Convert a String to Buffer
  36. Prevent Line Breaks in String Template Literals
  37. How to Implement a Custom `toString` Method
  38. What Is `Symbol.toStringTag` and How to Use It (Coming soon)

Convert a Date to UTC Timezone in JavaScript

JavaScript dates provide a handful of methods. A useful method for UTC conversion is the Date#toISOString function. The toISOString method converts a JavaScript date into a date time string format which is based on the ISO 8601 standard. The resulting date string is in the format of YYYY-MM-DDTHH:mm:ss.sssZ with UTC timezone, as represented by the Z suffix.

Here’s a sample function converting a given date to UTC:

/**
 * Returns the `date` as a UTC a date-time string.
 *
 * @param {Date} date
 *
 * @returns {String}
 */
function toUtc (date) {  
  if (!(date instanceof Date)) {
    throw new Error('You must pass a date argument to the "toUtc" method')
  }

  return date.toISOString()
}

You can use the toUTC function like this:

toUTC()  
// 💥 Error: You must pass a date argument to the "toUtc" method

toUtc(new Date('2024-12-25'))  
// '2024-12-25T00:00:00.000Z'

What About toUTCString?

JavaScript provides the Date#toUTCString() method that returns a string of a given date in the RFC 7231 format. This format allows negative years and the timezone is always UTC:

new Date('2024-12-25').toUTCString()  
// 'Wed, 25 Dec 2024 00:00:00 GMT'

The toUTCString() and toGMTString() methods are interchangeable and aliases for each other.

Using the Date#getUTC Methods

JavaScript dates also provide getUTC<unit> methods for each unit: year, month, day, hours, minutes, seconds, and milliseconds. You can use these methods if you want to convert selected parts of a given date to UTC.

Another use-case for these methods is when you’re using a different date format than the ISO 8601 date string.

Here’s the sample code using the getUTC<unit> methods to compose a date string without the T and Z characters.

const date = new Date()

const year = date.getUTCFullYear()  
const month = (date.getUTCMonth() + 1).toString().padStart(2, '0')  
const day = date.getUTCDate().toString().padStart(2, '0')

const hours = date.getUTCHours().toString().padStart(2, '0')  
const minutes = date.getUTCMinutes().toString().padStart(2, '0')  
const seconds = date.getUTCSeconds().toString().padStart(2, '0')  
const milliseconds = date.getUTCMilliseconds().toString().padStart(3, '0')

const utc = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`

console.log(utc)  
// '2024-06-09 04:40:38.058'

Use custom date formats with care because they may only apply to your application. A custom date format may cause hiccups when interacting with other services or when providing data via an API.

That’s it!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.