1

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 a 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 it's a simple question trying to edit codes of Codepen seems to mess one thing or another up for me always.

thanks.

norbekoff
  • 1,719
  • 1
  • 10
  • 21
annu
  • 11
  • 1
  • Welcome to stackoverflow. You can use https://momentjs.com/ this library there are many date time conversion methods. – Nirav Bhoi Sep 20 '22 at 18:20
  • 1
    Does this answer your question? [How do I format a date in JavaScript?](https://stackoverflow.com/questions/3552461/how-do-i-format-a-date-in-javascript) – Heretic Monkey Sep 20 '22 at 18:50
  • 1
    @NiravBhoi That site says that MomentJS is no longer maintained and should not be used for new development. Perhaps it's time to stop recommending it? – Heretic Monkey Sep 20 '22 at 18:51
  • try using [day.js](https://day.js.org/) – norbekoff Sep 20 '22 at 18:52

2 Answers2

0

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.

EssXTee
  • 1,783
  • 1
  • 13
  • 18
  • code works however it loads in really late for some reason? i have to wait literally a minute for the date to pop up after i load my page – annu Sep 20 '22 at 20:55
  • @annu The `setInterval` line has the function run once per minute (because seconds are not displayed), but the last line `_DateAndTime();` runs the function immediately. It runs fine here in the StackSnippet so are you sure you fully copied my code (including the last line to run the function immediately)? – EssXTee Sep 21 '22 at 11:38
  • i got it to work in the end by changing the 60000 to 0 lol works perfect now loads instantly in thanks bro, but what if i wanted to minus a few minutes from the current time how would i do that? so if i wanted it to appear as 22 Sept 2022 *current time minus 10 minutes*, the live time always being 10 minutes behind the actual time right now – annu Sep 22 '22 at 04:37
  • @annu Changing the `60000` to `0` means the `setInterval` function runs with an interval of zero. This is bad for performance as the `_DateAndTime()` function is essentially running non-stop with no delay (using up resources unnecessarily). If for some reason `_DateAndTime()` doesn't run when the page loads, you probably have this JavaScript ahead of your HTML (for example, loading in the `` instead of at the end of the `` (*check your browsers console `F12` for errors*). – EssXTee Sep 22 '22 at 11:43
  • @annu As for how to change the time difference, if you look at the second line of the function that updates the `#futureTime` element, you will see `new Date(Date.now()+36e5)`. This is taking `Date.now()` which is the current time and adding 1 hour to it (*in milliseconds*). `36e5` is the same as `3600000`. If you want to take away 10 minutes, you would subtract `600000` (*milliseconds*) or `6e5`. – EssXTee Sep 22 '22 at 11:46
-1
/**
 * 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());

Obie
  • 302
  • 3
  • 8