Format a UTC date as a YYYY-MM-DD hh:mm:ss string using Node.js

In this tutorial, we’ll explore how to format a UTC date as a string with the format YYYY-MM-DD hh:mm:ss using native JavaScript Date object methods.

While there are various libraries available for handling date formatting, we’ll focus on a solution that utilizes the built-in capabilities of Node.js.

Using the Date Object

JavaScript’s Date object provides the toISOString method, which returns a string representing the date in a simplified extended ISO format (ISO 8601). To achieve the desired format, we’ll make slight modifications to the ISO string.

Example

//Get the current UTC date as an ISO string
const isoString = new Date().toISOString();

//Modify the ISO string to the desired format
const formattedDate = isoString
  .replace(/T/, ' ')      // Replace T with a space
  .replace(/\..+/, '');   // Delete the dot and everything after

//Log the formatted date
console.log(formattedDate);

In this code snippet:

  • We create a new Date object to represent the current date and time.
  • We use the toISOString method to get a string in ISO8601 format.
  • We then apply two replace methods to modify the string. The first one replaces the ‘T’ character with a space, and the second one removes the dot and everything after it.
  • The resulting string is in the format YYYY-MM-DD hh:mm:ss and is logged to the console.

Output:

2024-01-15 09:22:33

One-liner approach

If you prefer a concise one-liner, you can chain the replace methods directly.

const formattedDateOneLiner = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');

console.log(formattedDateOneLiner);

This achieves the same result as the previous example but in a more compact form.

Now you have successfully formatted the current UTC date in the YYYY-MM-DD hh:mm:ss format using Node.js.

Other Date Formatting Libraries

While the above method is concise and doesn’t require external libraries, Node.js has several date formatting libraries that provide additional features and options. Here are some popular ones:

Day.js

Day.js is a fast, lightweight alternative to Moment.js with a similar API. You can install it using npm:

npm install dayjs

Usage:

const dayjs = require('dayjs');
const formattedDate = dayjs().format('YYYY-MM-DD HH:mm:ss');
console.log(formattedDate);

date-fns

date-fns is a small, fast library that works with standard JavaScript date objects. It’s a great alternative to Moment.js if you don’t need timezone support.

npm install date-fns

Usage:

const { format } = require('date-fns');
const formattedDate = format(new Date(), 'yyyy-MM-dd HH:mm:ss');
console.log(formattedDate);

Choose the method that best fits your project’s needs and preferences. Whether using the built-in Date object or a library, formatting UTC dates in Node.js is straightforward and flexible.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top