BraylanBB121
BraylanBB121

Reputation: 35

How can I calulate the time since 9:30 AM in JavaScript?

Okay, so I am trying to calculate the time since 9:30 in the morning in Google Apps Script, and I want the output to look like this: XX hrs XX mins. the problem is when I try calculating the minutes since 9:30, of course, it gives me all the minutes, not just the leftover minutes after I've calculated the hours. I need the minutes to be a decimal so I can times it by 60 and display the output in a cell. This is the code I'm currently using:

function CALCTIME() {
  const minutes = 1000 * 60;
  const hours = minutes * 60;
  const days = hours * 24;
  const years = days * 365;
  var now = new Date(),
  then = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate(),
    9,30,0),
  diff = now.getTime() - then.getTime();
  let hrs = diff / hours;
  let mins = Math.floor((diff / minutes) % 60);
  return Math.floor(hrs) + " hrs " + mins + " mins";
}

The issue is not the hrs, I have that all good. The minutes are the problem because I can't figure out how to replace just an index from a string. I've looked and tried the methods shown on these web pages and Stack Exchange links for answers and I couldn't find any:

https://www.w3schools.com/jsref/jsref_replace.asp

How do I replace a character at a particular index in JavaScript?

Questions: What do you expect these statements to do and why? mins.replaceAt(0, "0."); mins % 60; The first statement I expected to replace the first character in mins with "0." but then, @jabaa pointed out that I couldn't replace a number for a string, which I totally forgot and didn't take into account. The second statement I just forgot to put mins = mins % 60; which probably wouldn't have solved my problem anyway, I just forgot to put that there.

I've answered your questions, but someone has already answered my questions.

Upvotes: 0

Views: 81

Answers (1)

Edward
Edward

Reputation: 435

The reason it is not working is because you have:

diff = now.getTime() - then.getTime();

That line is going to get the time difference from now and 9:30am.

var hrs = diff / hours;
var mins = diff / minutes;

The two lines above are getting their own things. The first is how many hours and the second is how many minutes. So inherently you will be getting all the minutes and not the leftovers. There are multiple ways to fix it. Below is one way where the hours are right, so we take out every full hour from the minute's section.

Could look something like this:

let hrs = diff / hours;
let mins = (diff / minutes) % 60;

ALSO: The following line of code you have does nothing because you're not giving it anywhere to be stored in.

mins % 60

To fix you can do something like:

let testvar = mins % 60;

Upvotes: 1

Related Questions