ArticleZip > How To Output Date In Javascript In Iso 8601 Without Milliseconds And With Z

How To Output Date In Javascript In Iso 8601 Without Milliseconds And With Z

Outputting dates in JavaScript in ISO 8601 format without milliseconds and with "Z" at the end for the timezone is a common requirement when dealing with date and time values in web development. Fortunately, achieving this in JavaScript is straightforward with just a few lines of code.

To output the current date in ISO 8601 format without milliseconds and with the "Z" notation, you can use the following function:

Javascript

function getCurrentDateInISO8601() {
  const currentDate = new Date().toISOString().split('.')[0] + 'Z';
  return currentDate;
}

console.log(getCurrentDateInISO8601());

In the code snippet above, we first create a new `Date` object representing the current date and time. We then use the `toISOString()` method to convert this date to an ISO 8601 formatted string. The `toISOString()` method includes milliseconds by default, so we use the `split()` function to remove the milliseconds part, leaving us with just the date and time information. Finally, we append the "Z" at the end to indicate that the date is in UTC.

You can easily modify this function to output a specific date in ISO 8601 format without milliseconds and with the "Z" notation by passing a `Date` object as an argument. Here's an example illustrating this:

Javascript

function formatDateInISO8601(date) {
  const formattedDate = date.toISOString().split('.')[0] + 'Z';
  return formattedDate;
}

const customDate = new Date('2023-12-31T23:59:59');
console.log(formatDateInISO8601(customDate));

In the second code snippet, we define a more general `formatDateInISO8601` function that takes a `Date` object as a parameter and formats it accordingly. We pass a custom date `'2023-12-31T23:59:59'` to this function, and it outputs the date in the desired ISO 8601 format without milliseconds and with the "Z" notation.

Remember, when working with date and time values in JavaScript, always pay attention to the timezone implications. Adding the "Z" at the end of the ISO 8601 formatted date signifies that the date is in UTC. If you need dates in local time, you should adjust the code accordingly.

By following these simple steps, you can effectively output dates in the required ISO 8601 format without milliseconds and with the "Z" timezone notation in JavaScript, making your web development tasks more efficient and precise.