Anurag Bonde Anurag Bonde - 3 years ago 171
Javascript Question

JavaScript (Display date and time in specific format)

I know how to create date objects in JavaScript, but I am having difficulties displaying the date and time in the following format:

enter image description here

Answer Source

One possible Implementation

  • Start by creating two arrays, that will contain the abbreviated month names and day names respectively.
  • Create a new date using the 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.
  • From this new date object, create variables for the year, month, day, day name, hour minute and seconds respectively.
  • To get the suffix for the day, we need to use regex with the test function. Depending on the string implementation of the date, we will return a different suffix.
  • Finally, we can put this altogether with ES6 template strings. Enclose variables and expressions inside ${} 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}`);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download