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.
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;
I have an adobe pdf that calculates elapsed time, which is working. I however want to sum those times to give a total time in HH:MM format. enter image description here Anyone have any ideas on the javascript code that could do this?
enter image description here
In case i understand you correctly and you have an array of eplapsedTime as text,
You can run over the values and sum the hours in left part and minutes in right with split.
const flightTimes = ['09:12','12:13','02:55','23:40','05:59'];
let hours = 0, minutes = 0;
flightTimes.forEach((time) => {
const split = time.split(':');
hours += parseInt(split[0]);
minutes += parseInt(split[1]);
});
const formattedNumber = (num) => ("0" + num).slice(-2);
hours += Math.floor(minutes/60);
minutes = minutes % 60;
console.log(formattedNumber(hours) + ':' + formattedNumber(minutes));
On my project requires this kind of text response on a day and hours.
"2hrs"-- data as milliseconds, If i get 1h 30mins, It should be rounded-up to 2hrs.
i tried so many times but cannot catch the value. now am getting 1 hrs for below function.
can anyone help me to do this ? here is the function which i am using
const milliSec = 85600000;
const hrs = moment(moment.duration(milliSec)._data).format('HH[hrs]');
There are a couple of ways to solve your problem
Simple logic
let milliseconds = 85600000;
let hours = Math.floor(milliseconds/(1000*3600))
let minutes = Math.floor(milliseconds/(1000*60)) - hours * 60
if(minutes > 29){
console.log(hours + 1);
}
console.log(hours)
Using Moment.js
let milliseconds = 85600000
let hours = Math.floor(moment.duration(milliseconds).asHours())
let mins = Math.floor(moment.duration(milliseconds).asMinutes()) - hours * 60;
if(minutes > 29){
console.log(hours + 1);
}
console.log(hours)
Hope this helps you. Feel free for doubts.
I am currently working with hours as numbers, such as 2230 being equivalent to 22:30. I would like to be able to add numbers to it and sum as if they were minutes added to hours
2030 + 60 = 2130 //and not 2090
2330 + 120 = 0230 //and not 2350
Is there a library or function to doing this? Or perhaps I should change the way I am handling hours?
I don't recommend doing this, but if you want to do it, you have to handle the fact that you're pretending an hour is 100 minutes. You do that by extracting the real hours and minutes from the fake value, doing the math on them, and then reassembling them, something along these lines:
function toHoursAndMinutes(value) {
// Get hours: `value` divided by 100
const hours = Math.floor(value / 100);
// Get minutes: the remainder of dividing by 100
const minutes = value % 100;
// Return them
return [hours, minutes];
}
function fromHoursAndMinutes(hours, minutes) {
// Reassemble the number where hours are worth 100
return hours * 100 + minutes;
}
function add(a, b) {
// Get `a`'s hours and minutes
const [ahours, aminutes] = toHoursAndMinutes(a);
// Get `b`'s
const [bhours, bminutes] = toHoursAndMinutes(b);
// Add the hours together, plus any from adding the minutes
const hours = ahours + bhours + Math.floor((aminutes + bminutes) / 60);
// Add the minutes together, ignoring extra hours
const minutes = (aminutes + bminutes) % 60;
// Reassemble
return fromHoursAndMinutes(hours, minutes);
}
Live Example:
function toHoursAndMinutes(value) {
// Get hours: `value` divided by 100
const hours = Math.floor(value / 100);
// Get minutes: the remainder of dividing by 100
const minutes = value % 100;
// Return them
return [hours, minutes];
}
function fromHoursAndMinutes(hours, minutes) {
// Reassemble the number where hours are worth 100
return hours * 100 + minutes;
}
function add(a, b) {
// Get `a`'s hours and minutes
const [ahours, aminutes] = toHoursAndMinutes(a);
// Get `b`'s
const [bhours, bminutes] = toHoursAndMinutes(b);
// Add the hours together, plus any from adding the minutes
// The % 24 wraps around
const hours = (ahours + bhours + Math.floor((aminutes + bminutes) / 60)) % 24;
// Add the minutes together, ignoring extra hours
const minutes = (aminutes + bminutes) % 60;
// Reassemble
return fromHoursAndMinutes(hours, minutes);
}
console.log(add(2030, 60));
console.log(add(2330, 120));
But again, I don't recommend this. Instead, work with time values (Date or just milliseconds-since-the-Epoch, etc.) and convert for display when you need to display it.
Note that 50 rather than 0250, for two reasons: 1. 2330 + 120 is 2450 which is 00:50, not 02:50, and numbers don't have leading spaces except in string representations.
Here's my implementation of it
function add(current, time) {
const hours = Math.floor(time / 60);
const minutes = time % 60;
const currentMinutes = parseInt(current.toString().slice(2));
const currentHours = parseInt(current.toString().slice(0, 2));
const newMinutes = (currentMinutes + minutes) % 60;
const additionalHours = (currentMinutes + minutes) > 60 ? 1 : 0;
const newHours = (currentHours + hours + additionalHours) % 24;
return `${newHours < 10 ? '0' : ''}${newHours}${newMinutes < 10 ? '0' : ''}${newMinutes}`;
}
console.log(add(2030, 60)); // 2130
console.log(add(2330, 120)); // 0130
here is the working code for your clock.
var nowTime = '2350'; //current time in String..
var newMin = 120; // min you want to add in int..
var tMinutes = parseInt(nowTime.toString().slice(2)); //taking out the min
var tHours = parseInt(nowTime.toString().slice(0, 2)); //taking out the hr
var newMinutes = (newMin + tMinutes) % 60;
var newHr = tHours + parseInt(((newMin + tMinutes) / 60));
var newTime = `${newHr >= 24 ? newHr-24 : newHr}${newMinutes}`;
newTime = newTime.length < 4 ? '0'+newTime : newTime;
console.log(newTime);
If you want to handle date math, a library is probably best, because date math is hard, and the source of so many bugs if done wrong. Now, knowing how to do date math is a great thing to learn though, and reading through the source code of date math libraries is a good way to do that. Luxon is a good library with duration objects that can do what you need easily, and has readable source code. Other duration libraries also exist, so take a look at a few of those and see what you like the best. You can also abuse he built-in Date library to act like a duration object, but I don't think that's worth it.
But libraries aside, let's analyze the problem and what you might want to consider in solving it.
First off, I would say your first problem is trying to use a data type that isn't designed for what you want. A single integer is not a good idea for representing two values with different units. That is sort of what T.J. meant when he said it's a presentation concept. You have one object, but it's not really an integer in behavior. And date is close, but not quite right. So let's make a class. Duration seems like a good name:
class Duration { … }
We know it has two parts, hours and minutes. Also, it seems a good idea to just use one unit and convert them. (You wouldn't have to, but it actually makes the math easier if you do the conversion):
class Duration {
constructor ({hours = 0, minutes = 0}) {
this.totalMinutes = hours * 60 + minutes
}
}
Now lets make some getters to get just the minutes section and the hours section:
class Duration {
…
// just minutes that don't fit in hours
get minutes () { return this.totalMinutes % 60 }
get hours () { return Math.floor(this.totalMinutes / 60) }
// and also let's present it as the string you wanted:
asDisplayString() { return `${this.hours*100 + this.minutes}` }
}
Now we need to add them together. Some languages would let you use + for this, but javascript has limits on what we can make + do, so we'll add our own method. Note that because of how our constructor works, we can have more than 60 minutes when we initialize the values. Is this a good idea? Maybe. Depends on how you want the object to behave. (While we'll go with it for this example, there are definite arguments against it, mostly because it is a bit confusing that get minutes doesn't return over 60 - but it's also makes a certain sense at the same time).
class Duration {
…
add (otherDuration) {
return new Duration({minutes: this.totalMinutes + otherDuration.totalMinutes})
}
}
And now we can add our duration objects together, and the math is taken care of for us.
class Duration {
constructor ({hours = 0, minutes = 0}) {
this.totalMinutes = hours * 60 + minutes
}
// just minutes that don't fit in hours
get minutes () { return this.totalMinutes % 60 }
get hours () { return Math.floor(this.totalMinutes / 60) }
// and also let's present it as the string you wanted:
asDisplayString() { return `${this.hours*100 + this.minutes}` }
add (otherDuration) {
return new Duration({minutes: this.totalMinutes + otherDuration.totalMinutes})
}
}
d1 = new Duration({hours:20, minutes: 30})
d2 = new Duration({minutes: 50})
console.log(d1.asDisplayString(), '+', d2.asDisplayString(), '=', d1.add(d2).asDisplayString())
I have the following code for showing how long ago a comment was made:
var timestamp = (new Date().getTime())/1000;
var comment_time = timestamp - responses[i]['time'];
var time_string = '';
if(comment_time < 60)
time_string = Math.round(comment_time)+"s ago";
else if(comment_time < 3600)
time_string = Math.round(comment_time/60)+"m ago";
else if(comment_time < 86400)
time_string = Math.round(comment_time/3600)+"h ago";
else
time_string = Math.round(comment_time/86400)+"d ago";
This works just fine, unless the comment is less than a minute old. When that happens, no rounding occurs at all. It looks like I'm getting a consistent 15 significant digits if the comment is less than one minute old. Once it gets older than one minute, everything works fine. What can be done about this?
Try using the parseInt() with fractional parts
time_string = parseInt(Math.round(comment_time/60))+"m ago";
also go get it in there with jsfiddle
http://jsfiddle.net/arunpjohny/6m5D8/1/