I know how to create date objects in JavaScript, but I am having difficulties displaying the date and time in the following format:
One possible Implementation
Date
constructor. In this case, we will pass in the year, month, day of the month, hour, minutes and seconds respectively. There are a few things to keep in mind here. Months start at 0 instead of 1, so to get the third month of the year (March) you would have to pass in 2. Hours range from 0 to 23, so we need to pass in 17 instead of 5.test
function. Depending on the string implementation of the date, we will return a different suffix.${}
and place the string in backticks.var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
// Create a new date object and variables based upon this object
var date = new Date(2012,2,13,17,8,57);
var year = date.getFullYear();
var month = months[date.getMonth()];
var day = date.getDate();
var dayName = days[date.getDay()];
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
// Control formatting of time
var timePeriod = hour > 12 ? "PM" : "AM";
hour = hour < 10 ? "0" + hour : hour > 12 ? ((hour % 12) < 10 ? "0" + hour % 12 : hour % 12) : hour;
minute = minute < 10 ? "0" + minute : minute;
second = second < 10 ? "0" + second : second;
// Return the suffix of the day
day = /[4567890]$|11|12|13/.test(day) ? day + "th" :
/^1$|21|31/.test(day) ? day + "st" :
/^2$|22/.test(day) ? day + "nd" : day + "rd";
// Log the results
console.log(`${dayName} ${month} ${day}, ${year}, ${hour}:${minute}:${second} ${timePeriod}`);