JavaScript: How to create a formatted date time string

In JavaScript, to get today’s date and time, all we need to do is use a call to Date() For example:

let today = new Date();

This gives us today’s date and the current time, in the form of a Date object that looks like this:

‘Date’ is the key (left), and the value is an ISO date string (right).

Date 2018-04-10T01:44:37.812Z

In JavaScript dates are typically stored as an ISO date-time string. This has the following format:

“2017-04-18T05:00:00.000Z

The T in the middle separates the date on the left from the time on the right. The Z at the end is a time zone indicator which means use UTC (Coordinated Universal Time).

Let’s say we are given an ISO date-time string and we want to output a formatted string for a website, that looks like:

04/9/18 8:00 PM

We can do this with the following function:

const formatDateTime = function (isoDate){
  // Function takes in an ISO date of the format 
  // "2017-04-18T05:00:00.000Z" and returns a formatted
  // date + time string that looks like this: mm/dd/yy hh:mm pm
  datetime = new Date(isoDate);
  day = datetime.getDate();
  month = datetime.getMonth() + 1; //month: 0-11
  year = datetime.getFullYear();
  year = year.toString().slice(-2); // use 2 digit year
  dateString = month + "/" + day + "/" + year;
  let options = { hour: 'numeric', minute: 'numeric', hour12: true };
  let timeString = datetime.toLocaleString('en-US', options);
  let formattedDateTime = dateString + ' ' + timeString;
  return formattedDateTime;
}

This function can be called like this:

let formattedDate = formatDateTime("2017-04-18T05:00:00.000Z");

For more information about using the toISOString() function, see:
https://www.w3schools.com/jsref/jsref_toisostring.asp

For more information about JavaScript dates and date functions, see:
https://www.w3schools.com/jsref/jsref_obj_date.asp
https://www.w3.org/TR/NOTE-datetime