let date = new Date();
console.log(date.toISOString()); // Outputs: "2024-02-09T18:11:17.000Z"

The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ. The timezone is always zero UTC offset.

Using toString()

The toString() method converts a Date object to a string in the following format: Day Month Date Year Time (Time Zone).

let date = new Date();
console.log(date.toString()); // Outputs: "Fri Feb 09 2024 18:11:17 GMT+0000 (Coordinated Universal Time)"

Custom Formatting

Once you’ve converted your Date object to a string, you might want to format it in a specific way. JavaScript doesn’t have a built-in date-formatting function, but you can manually construct a formatted string using various Date methods:

let date = new Date();
let formatted = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
console.log(formatted); // Outputs: "2024-2-9 18:11:17"

This will output a string in the format “YYYY-M-D HH:mm:ss”. Notice that getMonth() returns a zero-based value (0 for January, 1 for February, etc.), so we add 1 to get the correct month number.

Intl.DateTimeFormat()

The Intl.DateTimeFormat object is part of JavaScript’s built-in internationalization API. It allows you to format date and time according to different locales, providing a more user-friendly way to display dates and times to users around the world.

Here’s a basic example of how to use it:

let date = new Date();
let formatter = new Intl.DateTimeFormat('en-US');
console.log(formatter.format(date)); // Outputs date in 'en-US' format like "2/9/2024"

In the above example, we’re creating a new Intl.DateTimeFormat object with ‘en-US’ locale, which formats the date in Month/Day/Year format.

You can also customize the options to format the date in a specific way:

let date = new Date();
let options = { year: 'numeric', month: 'long', day: 'numeric' };
let formatter = new Intl.DateTimeFormat('en-US', options);
console.log(formatter.format(date)); // Outputs "February 9, 2024"

In this snippet, we’re passing an options object to Intl.DateTimeFormat to specify that we want a numeric year, a long-form month, and a numeric day.

The Intl.DateTimeFormat object supports many different options, allowing you to customize the date and time format as needed. For more information and a full list of options, check out the MDN Documentation.

Remember, not all browsers fully support the Intl object, so make sure to check browser compatibility when using it.

Bonus function

This is a function I wrote myself and I was inspired by PHP’s great date_format() function. I think it’s a pity that JavaScript doesn’t have such a versatile yet simple function built in.

function dateFormat(date, format) {
  const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  const shortDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  const shortMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

  let hour = date.getHours();
  let isPM = hour >= 12;
  let hour12 = hour > 12 ? hour - 12 : (hour === 0 ? 12 : hour);

  const map = {
    'Y': date.getFullYear(),
    'y': ('' + date.getFullYear()).slice(-2),
    'm': ('0' + (date.getMonth() + 1)).slice(-2),
    'd': ('0' + date.getDate()).slice(-2),
    'H': ('0' + date.getHours()).slice(-2),
    'i': ('0' + date.getMinutes()).slice(-2),
    's': ('0' + date.getSeconds()).slice(-2),
    'l': days[date.getDay()],
    'D': shortDays[date.getDay()],
    'F': months[date.getMonth()],
    'M': shortMonths[date.getMonth()],
    'h': ('0' + hour12).slice(-2),
    'g': hour12,
    'A': isPM ? 'AM' : 'PM',
    'a': isPM ? 'am' : 'pm'
  };

  return format.replace(/Y|y|m|d|H|i|s|l|D|F|M|h|g|A|a/gi, matched => map[matched]);
}

let date = new Date();
console.log(dateFormat(date, 'l, F d, Y h:i:s A')); // Outputs: "Friday, February 09, 2024 07:15:05 PM"

Use a library

If your use case is simple, then you’re better off using one of the methods I mentioned above. But if you believe you will be working a lot with dates and times in your application, you might want to consider using a library. Working with dates and times can be tricky and using a library will save you the headache.

JavaScript libraries like Moment.js, date-fns, and Luxon can help with date formatting. Moment.js has lots of options but is large in size. If you’re concerned about performance, date-fns is smaller because it’s modular – you only import what you need. Luxon, made by a Moment.js developer, improves on some areas of Moment.js.

Here are examples of how to format a date using each library:

Moment.js:

let moment = require('moment');
let date = moment().format('YYYY-MM-DD HH:mm:ss');
console.log(date); // Outputs current date & time in the format "2024-02-09 19:21:32"

date-fns:

let format = require('date-fns/format');
let date = format(new Date(), 'yyyy-MM-dd HH:mm:ss');
console.log(date); // Outputs current date & time in the format "2024-02-09 19:21:32"

Luxon:

let { DateTime } = require('luxon');
let date = DateTime.now().toFormat('yyyy-MM-dd HH:mm:ss');
console.log(date); // Outputs current date & time in the format "2024-02-09 19:21:32"

Similar Posts