display the current day and time

Write a JavaScript program to display the current day and time in the following format. Sample Output : Today is : Friday. Current time is : 4 PM : 50 : 22

by Shridhar Baddur

JavaScript

/*

Write a JavaScript program to display the current day and time in the following format.
Sample Output : Today is : Friday. 
Current time is : 4 PM : 50 : 22

*/

function timeStamp() {

  //Create the output format string and initialise to the empty string.
  var output = "";

  // Create a date object with the current time
  var now = new Date();

  //Define weekdays to find the current day of the week
  var weekday = new Array(7);
  weekday[0] = "Sunday";
  weekday[1] = "Monday";
  weekday[2] = "Tuesday";
  weekday[3] = "Wednesday";
  weekday[4] = "Thursday";
  weekday[5] = "Friday";
  weekday[6] = "Saturday";

  // Create an array with the current hour, minute and second
  var time = [now.getHours(), now.getMinutes(), now.getSeconds()];

  // Determine AM or PM suffix based on the hour
  var suffix = (time[0] < 12) ? "AM" : "PM";

  // Convert hour from military time
  time[0] = (time[0] < 12) ? time[0] : time[0] - 12;

  // If hour is 0, set it to 12
  time[0] = time[0] || 12;

  //Attach the suffix to match sample output format
  time[0] = time[0] + suffix;
  // If seconds and minutes are less than 10, add a zero
  for (var i = 1; i < 3; i++) {
    if (time[i] < 10) {
      time[i] = "0" + time[i];
    }
  }

  //getDay will Return the day of the week
  output = "Today is : " + weekday[now.getDay()] + "\nCurrent Time is : " + time.join(" : ");

  //Return the output
  return output;
}

console.log(timeStamp());