Home > Net >  how to display current time and dates html
how to display current time and dates html

Time:09-21

I'm trying to display the current time and date on my website but having issues because I need it displayed a certain way and with an hour added ahead.

For the first one I need it displayed like this:

20 Sep 2022 *current time* (12 hour format with am and pm)

second one:

20 Sep 2022 *current time  1hr* (12 hour format with am and pm)

I tried this code of Codepen but I need the time displayed after the date and it also shows as short date on my site for some reason.

function DateAndTime() {
  var dt = new Date();

  var Hours = dt.getHours();
  var Min = dt.getMinutes();
  var Sec = dt.getSeconds();

  var days = [
    "",
    "",
    "",
    "",
    "",
    "",
    ""
  ];

  //strings
  var months = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "June",
    "July",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec"
  ];

  if (Min < 10) {
    Min === "0"   Min;
  } //displays two digits even Min less than 10

  if (Sec < 10) {
    Sec === "0"   Sec;
  } //displays two digits even Sec less than 10

  var suffix = "AM"; //cunverting 24Hours to 12Hours with AM & PM suffix
  if (Hours >= 12) {
    suffix = "PM";
    Hours = Hours - 12;
  }
  if (Hours === 0) {
    Hours = 12;
  }

  document.getElementById("time").innerHTML =
    Hours   "Hours : "   Min   "Min : "   Sec   "Sec "   suffix   ".";
  document.getElementById("date").innerHTML =
    days[dt.getDay()]  
    ", "  
    dt.getDate()  
    " "  
    months[dt.getMonth()]  
    " "  
    dt.getFullYear();
}

new DateAndTime();
setInterval("DateAndTime()", 1000);

the above code shows like this:

7Hours : 9Min : 47Sec PM.

, 20 Sep 2022 

I need it displayed like this

20 Sep 2022 7:10 pm

20 Sep 2022 8:10 pm (one hour added to current time)

I'm pretty new to coding so sorry if its simple question trying to edit codes of Codepen seems to mess one thing or another up for me always.

thanks.

CodePudding user response:

You can actually get (almost exactly) the result you want using the toLocaleDateString() method in JavaScript. This essentially spits out a date string based on a Date object, and you can pass in options to alter the format of the date/time.

There is a more in-depth explaination on the MDN Web Docs, but you simply pass in the locale for the date, and then any options for how to format each part of the date.

const _DateAndTime = () => {
  document.querySelector("#currentTime").innerHTML = new Date().toLocaleDateString('en-gb', {year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric', hour12: true});
  document.querySelector("#futureTime").innerHTML = new Date(Date.now() 36e5).toLocaleDateString('en-gb', {year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric', hour12: true});
}

setInterval(_DateAndTime, 60000);
_DateAndTime();
<div id="currentTime"></div>
<div id="futureTime"></div>

Notes

I am using the en-gb locale because it uses the dd/mm/yyyy format, as opposed to en-us which uses mm/dd/yyyy. There are probably other locales that can be used to display the month as Sep instead of Sept, but it was close enough to where I didn't consider it to be an issue.

CodePudding user response:

/**
 * Get am or pm based on hour
 * @param {number} hour
 * @returns {string} am or pm
 */
function getAmPm(hour) {
  return hour >= 12 ? "pm" : "am";
}

/**
 * Get hour in 12 hour format
 * @param {number} hour
 * @returns {number} hour in 12 hour format
 */
function getHour12(hour) {
  return hour % 12 || 12;
}

/**
 * Get the currentDate and currentDate plus 1 hour
 * @returns {{ currentDate: string, currentDatePlus1Hour: string }}
 */
function getDateAndTime() {
  const date = new Date();

  const months = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec",
  ];

  const day = date.getDate();
  const month = date.getMonth();
  const year = date.getFullYear();

  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  const hourPlusOne = hour   1;

  const currentDate = `${day} ${months[month]} ${year} ${getHour12(
    hour
  )}:${minute}:${second} ${getAmPm(hour)}`;
  const currentDatePlus1Hour = `${day} ${months[month]} ${year} ${getHour12(
    hourPlusOne
  )}:${minute}:${second} ${getAmPm(hourPlusOne)}`;

  return { currentDate, currentDatePlus1Hour };
}

console.log(getDateAndTime());

  • Related