4

How would I bring together my checkTime and checkMinute function into one so that when I do an offset of (m + 30) it will also make h go to the next hour when m reaches 60. Thanks!

Currently My code tells the time and can take on offset for hours on a 24 hour scale, my issue is it does not allow me to change the code in offset of + 30 minutes which I would like the ability to do.

My if statements aren't getting me the outcome I want which is when minutes hit 60 from doing an offset of + 30 then the hour will go to the next one instead of only affecting the minutes.

I believe I would need to bring the two function together but am not sure how to do this accurately.

function addLeadingZero(n) {
  return n < 10 ? '0' + n : n;
}

function timeClock(timeZoneOffset) {
  var d = new Date();
  d.setHours(d.getUTCHours() + timeZoneOffset); // set time zone offset
  var h = d.getUTCHours();
  var m = d.getUTCMinutes();
  var s = d.getUTCSeconds();
  /*    h = h % 12;
      h = h ? h : 12; // replace '0' w/ '12'  */
  /*  h = checkHour(h)  */
  m = checkTime(m);
  s = checkTime(s);
  h = addLeadingZero(h);

  document.all["txt3"].innerHTML = /*+ checkHour*/ (h - 4) + ':' + m + ':' + s + ' ';
  document.all["txt1"].innerHTML = /*+ checkHour*/ (h + 3) + ':' + m + '' + ' ';
  document.all["txt2"].innerHTML = h + ':' + checkMinute(m + 30) + '' + ' ';
  document.all["txt4"].innerHTML = h + ':' + m + '' + ' ';
  document.all["txt5"].innerHTML = h + ':' + m + '' + ' ';
  setTimeout(function() {
    timeClock(timeZoneOffset)
  }, 500);
}

function checkTime(i) {
  var j = i;
  if (i < 10) {
    j = "0" + i;
  }
  return j;
}

function checkHour(i) {
  var j = i;
  if (i > 23) {
    j = j - 24;
  }
  if (i < 0) {
    j = "0" + i;
  }
  return j;
}

function checkMinute(i) {
  var j = i;
  if (i > 59) {
    j = j - 60;
  }
  if (i < 0) {
    j = "0" + i;
  }
  return j;
}

/* setInterval(function() {
      startTime();
      }, 500);
    })(jQuery);    */

window.onload = function() {
  timeClock(2);
}
<div id="txt3"></div>
<div id="txt1"></div>
<div id="txt2"></div>
<div id="txt4"></div>
<div id="txt5"></div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    document.all is a remnant for IE from before the millenium... Your code can easily updated to 2020 – mplungjan Mar 19 '20 at 14:30
  • ALso why use checkTime, when you have addLeadingZero and you are not using checkHour – mplungjan Mar 19 '20 at 14:31
  • @mplungjan How would I update document.all? Im not to familiar with any other methods. And I removed checkTime. I did not notice it repeated addLeadingZero – Johnlovescode Mar 19 '20 at 14:49
  • @mplungjan is there away I can make one function do what addLeadingZero, and checkHour does in one – Johnlovescode Mar 19 '20 at 14:52
  • My answer does not even need the `const pad = (num) => ("0" + num).slice(-2);` I wrote to replace your addLeadingZero ;) – mplungjan Mar 19 '20 at 15:00
  • document.all was never needed beyond IE4. - one could use document.getElementById/document.geteElementsByName and document.getElementsByTagName which is now document.querySelector or document.getElementById if it has an ID – mplungjan Mar 19 '20 at 15:23

2 Answers2

5

To be precise: Welcome to 2020 ;)

for info : -- list of TZ -> https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

-- Date.toLocaleString usage -> https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Date/toLocaleString

[edit] added military time (without seconds and : separator)

first version with civil and military times

const OptionsCivil    = { hour12:true,  hour:'numeric', minute:'2-digit', second:'2-digit' };  
const OptionsMilitary = { hour12:false, hour:'2-digit', minute:'2-digit' };

const CivilTime=(dt,dz)=>dt.toLocaleString("en-GB", {...OptionsCivil, timeZone:dz })

const MilitaryTime=(dt,dz)=>
  {
  let rep = dt.toLocaleString("en-US", {...OptionsMilitary, timeZone:dz }).replace(/:/g,'')
  return (rep==='0000') ? 2400 : rep.replace(/^24/, '00'); // specific browsers marmelade
  }

setInterval(() => {
  let d = new Date();
  document.querySelectorAll('.timZon')
            .forEach(el=> el.textContent = CivilTime(d, el.dataset.timeZone));
  document.querySelectorAll('.timZonM')
            .forEach(el=> el.textContent = MilitaryTime(d, el.dataset.timeZone));
}, 1000);

/* or more concise :
setInterval(() => {
  let d = new Date();
  document.querySelectorAll('.timZon, .timZonM')
           .forEach(el=>el.textContent =(el.classList.contains('timZonM')?MilitaryTime:CivilTime)(d, el.dataset.timeZone));
}, 1000);
*/
div.timZon,
div.timZonM {
  width       : 7em;
  text-align  : right;
  margin      : .4em;
  color       : deeppink;
  font-family : 'Courier New', Courier, monospace;
}
div.timZonM { /* military time */
  width  : 3em;
  color  : navy;
}

/* css tooltip code for displaying timeZone value
   ----------------> irrelevant part, can be removed) */
div[data-time-zone] {
  cursor    : crosshair;
  position  : relative;
  }
div[data-time-zone]:hover {
  background-color : yellow;
  }
div[data-time-zone]:hover:before {
  position         : absolute;
  font-size        : .8em;
  top              : 1.7em;
  border-radius    : .8em;
  content          : 'TZ: ' attr(data-time-zone);
  background-color : darkblue;
  color            : whitesmoke;
  white-space      : nowrap;
  z-index          : 1000;
  padding          : .4em .6em;
  }
<div class="timZon"  data-time-zone="America/New_York" ></div>
<div class="timZonM" data-time-zone="America/New_York" ></div>
<div class="timZonM" data-time-zone="Asia/Kolkata"></div>
<div class="timZonM" data-time-zone="Europe/Paris"></div>
<div class="timZonM" data-time-zone="Australia/Adelaide"></div>
<div class="timZonM" data-time-zone="Etc/GMT"></div>
<div class="timZonM" data-time-zone="Etc/GMT+4"></div>
<div class="timZonM" data-time-zone="Etc/GMT-5"></div>

After the last comments here is a version only with military times, the first on the list to be the only one to indicate the seconds

const OptionsMilitary = { hour12:false, hour:'2-digit', minute:'2-digit', second:'2-digit' };

const MilitaryTime=(elm, dt)=>
  {
  let [hh,mm,ss] = dt.toLocaleString("en-US", {...OptionsMilitary, timeZone:elm.dataset.timeZone }).split(':') 
  if ('seconds'in elm.dataset) elm.dataset.seconds = ':'+ss
  elm.textContent = (hh=='00'&&mm=='00') ? '2400' : (hh+mm).replace(/^24/, '00'); // specific browsers marmelade
  }

setInterval(() => {
  let dateTime = new Date();
  document.querySelectorAll('.timZonM').forEach(el=>MilitaryTime(el, dateTime));
}, 1000);
div.timZonM { /* military time */
  width          : 3em;
  margin         : .3em;
  color          : navy;
  font-size      : 20px;
  font-family    : 'Courier New', Courier, monospace;
  letter-spacing : .05em;
  }
div.timZonM::after {
  content : attr(data-seconds);
  color   : crimson;
  }

/* css tooltip code for displaying timeZone value
   ----------------> irrelevant part, can be removed) */
div[data-time-zone] {
  cursor    : crosshair;
  position  : relative;
  }
div[data-time-zone]:hover {
  background-color : yellow;
  }
div[data-time-zone]:hover:before {
  position         : absolute;
  font-size        : .8em;
  top              : 1.7em;
  border-radius    : .8em;
  content          : 'TZ: ' attr(data-time-zone);
  background-color : darkblue;
  color            : whitesmoke;
  white-space      : nowrap;
  z-index          : 1000;
  padding          : .4em .6em;
  }
<div class="timZonM" data-time-zone="America/New_York"></div>
<div class="timZonM" data-time-zone="Asia/Kolkata"></div>
<div class="timZonM" data-time-zone="Europe/Paris" data-seconds></div> <!-- add data-seconds to show seconds value -->
<!-- as much as you want... -->
<div class="timZonM" data-time-zone="Australia/Adelaide"></div>
<div class="timZonM" data-time-zone="Asia/Kathmandu"></div>
<div class="timZonM" data-time-zone="Etc/GMT"></div>
<div class="timZonM" data-time-zone="Etc/GMT+4" data-seconds></div>
<div class="timZonM" data-time-zone="Etc/GMT-5"></div>

for horizontaly display use css flex box

const OptionsMilitary = { hour12:false, hour:'2-digit', minute:'2-digit', second:'2-digit' }
  ,   timZonMil_All   = document.querySelectorAll('div.timZonMil > div')
  ;
const MilitaryTime=(elm, dt)=>
  {
  let [hh,mm,ss] = dt.toLocaleString("en-US", {...OptionsMilitary, timeZone:elm.dataset.timeZone }).split(':')
  elm.textContent = (hh=='00'&&mm=='00') ? '2400' : (hh+mm).replace(/^24/, '00'); // specific browsers marmelade
  if ('seconds' in elm.dataset) elm.innerHTML  += `<span>:${ss}</span>` 
  }
setInterval(() => {
  let dateTime = new Date();
  timZonMil_All.forEach(el=>MilitaryTime(el, dateTime));
}, 500);
div.timZonMil {
  display         : flex;
  justify-content : space-between;
  min-width       : 100vw;
  position        : absolute;
  top             : 123px;
  color           : navy;
  font-size       : 20px;
  font-family     : 'Courier New', Courier, monospace;
  letter-spacing  : .05em;
  }
div.timZonMil > div {
  min-width   : 3.6em;
  text-align  : center;
  }
div.timZonMil > div[data-seconds] {
  min-width   : 5.2em;
  }
div.timZonMil > div > span {
  color       : crimson;
  }

/* css tooltip code for displaying timeZone value
   ----------------> irrelevant part, can be removed) */
div[data-time-zone] {
  cursor    : crosshair;
  position  : relative;
  }
div[data-time-zone]:hover {
  background-color : yellow;
  }
div[data-time-zone]:hover:before {
  position         : absolute;
  font-size        : .8em;
  top              : 1.7em;
  border-radius    : .8em;
  content          : 'TZ: ' attr(data-time-zone);
  background-color : darkblue;
  color            : whitesmoke;
  white-space      : nowrap;
  z-index          : 1000;
  padding          : .4em .6em;
  }
<div class="timZonMil" >
  <div data-time-zone="Asia/Tehran"></div>
  <div data-time-zone="Etc/GMT"    ></div>
  <div data-time-zone="Etc/GMT+4"  data-seconds ></div>
  <div data-time-zone="Etc/GMT-8"  ></div>
  <div data-time-zone="Etc/GMT-14" ></div>
</div>

I also changed second display method, regarding ypur last message

Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
  • Awesome! Thank you ! Also if I would like to edit the timezone further would I do so in HTML by just changing the data-time-zone="" to the timezone I want? – Johnlovescode Mar 19 '20 at 16:19
  • @Johnlovescode Yes, you can put the time zone label of your choice in as many divs as you want, I added in my post the reference to have the list of all possible TZs. – Mister Jojo Mar 19 '20 at 16:41
  • What is the need for `return (rep==='0000') ? 2400 : rep.replace(/^24/, '00');` ? JS has 0 based 24 hour time as default – mplungjan Mar 19 '20 at 19:02
  • @Johnlovescode this is because FireFox display `0000` instead of `2400`, and Chrome display `2403` instead of `0003`, so this code part correct this probem – Mister Jojo Mar 19 '20 at 19:06
  • @MisterJojo Thank you I decided to use your answer. Only question how would I get rid of am in civil time as I do not want it displayed – Johnlovescode Mar 23 '20 at 14:37
  • @MisterJojo Sure how do I validate your code im new to this website. And also the only time I want to change is the civil time to not display am or pm but still want the seconds to show. Is that possible to only remove the am or pm from civil time and still get seconds or is it possible to do military time and add the seconds because ultimately that is what I want for only one of the clocks to display – Johnlovescode Mar 23 '20 at 15:15
  • @MisterJojo Okay. Thank you. I accepted your answer also. But yes all I would like is for the civil time in pink to display in this format 1200:53 where the hours and minutes are together and the seconds are separated by ":" and no am or pm present. – Johnlovescode Mar 23 '20 at 15:27
  • @MisterJojo Would be greatly appreciated, but thanks for all of your help so far – Johnlovescode Mar 23 '20 at 15:27
  • @MisterJojo Just an update I was able to remove the am pm like wanted, but still am unable to figure out the other part so you don't need to waste time on removing the am pm. – Johnlovescode Mar 23 '20 at 16:04
  • @MisterJojo No, what you have is perfect! My only problem is I'm trying to display the time with seconds for my third time and for some reason its going to the time at the top. How would I make another function one for the one that will display seconds and another for one that will display military time. Sorry for the complication – Johnlovescode Mar 23 '20 at 18:19
  • @MisterJojo In simpler terms because I'm rambling I guess what I'm trying to do is have 5 clocks total. And be able add seconds to the third clock only with a separator. – Johnlovescode Mar 23 '20 at 18:27
  • @Johnlovescode just change `(i===0)` to `(i===2)` in the js code. (count start at zero) – Mister Jojo Mar 23 '20 at 18:31
  • @MisterJojo You are awesome. THANKS! – Johnlovescode Mar 23 '20 at 18:36
  • @Johnlovescode very last change forever: you can set the display second if the ` – Mister Jojo Mar 23 '20 at 19:00
  • @MisterJojo Thanks friend. I really appreciate your help ;) – Johnlovescode Mar 23 '20 at 20:56
  • @MisterJojo this is a different question then I asked previously but I needed help and thought you may be able to assist. This is the HTML and Javascript for my current design. I want the ability to change the hours offset on another customization page and for those changes to apply to the display page that the clocks are on. I currently change the offsets from the display page by typing in the TimeZone database name or by typing in the correct timezone offset. So in simple terms I am trying to change the timezone input from another webpage and have it still displayed from my display webpage – Johnlovescode Apr 02 '20 at 14:38
  • @MisterJojo HTML:
    – Johnlovescode Apr 02 '20 at 14:40
  • @MisterJojo Javascript code: const OptionsMilitary = { hour12:false, hour:'2-digit', minute:'2-digit', second:'2-digit' }; const MilitaryTime=(elm, dt)=> { let [hh,mm,ss] = dt.toLocaleString("en-US", {...OptionsMilitary, timeZone:elm.dataset.timeZone }).split(':') if ('seconds'in elm.dataset) elm.dataset.seconds = ':'+ss elm.textContent = (hh=='00'&&mm=='00') ? '2400' : (hh+mm).replace(/^24/, '00'); // specific browsers marmelade } setInterval(() => { let dateTime = new Date(); document.querySelectorAll('.timZonM').forEach(el=>MilitaryTime(el, dateTime)); }, 500); – Johnlovescode Apr 02 '20 at 14:40
  • @MisterJojo here is also the link to this question if you would be interested in answering it here https://stackoverflow.com/questions/60935454/how-to-make-edits-on-webpage-that-change-display-on-another-webpage?noredirect=1#comment107810208_60935454 – Johnlovescode Apr 02 '20 at 14:41
  • @Johnlovescode adding new display system, on the same line, with other method to display seconds – Mister Jojo Apr 03 '20 at 01:57
2

Welcome to 2020 ;)

For HHMM military time you can use

const pad = (num) => ("0" + num).slice(-2);
....
const [hh,mm,ss] = d.split(", ")[1].split(":");
document.querySelector("#" + t).innerHTML = pad(hh)+pad(mm)

const timeObj = {
  "txt1": {
    "tz": "America/New_York",
    "locale": "en-US"
  },
  "txt2": {
    "tz": "Asia/Kolkata",
    "locale": "en-IN"
  },
  "txt3": {
    "tz": "Europe/Berlin",
    "locale": "de-DE"
  }
};

const timeClock = () => {
  for (t in timeObj) {
    const tObj = timeObj[t];
    let d = new Date().toLocaleString(
      tObj.locale, { "timeZone": tObj.tz })
    document.querySelector("#" + t).innerHTML = d.split(", ")[1];
  }
};
setInterval(timeClock, 500);
div {
  width: 100px;
  text-align: right
}
<div id="txt1"></div>
<div id="txt2"></div>
<div id="txt3"></div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236