How do I add minutes so they turn into hours? - addition

This may be a simple question but how do I add minutes so they will turn into hours i.e. if you add 30 minutes and 30 minutes and 30 minutes it will give an answer of 1 hour and 30 minutes?
So far I just have the minutes totalling:
function findTotalHours(){
var arr = document.getElementsByName('hours');
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('totalHoursv').value = tot;
}
function findTotalMins(){
var arr = document.getElementsByName('minutes');
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('totalMins').value = tot;
}
I have created a js fiddle to show the table which isn't working correctly...ie it is giving 90 minutes as answer
https://jsfiddle.net/Vicky1984/kLurp45y/9/
Any advice greatly appreciated, I'm totally new to javascript
thanks

function findTotalHours(){
var arr = document.getElementsByName('hours');
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
return tot;
}
function findTotalMins(){
var arr = document.getElementsByName('minutes');
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
return tot;
}
function calculateAllocation(){
var mins = findTotalMins();
var hrs = findTotalHours();
hrs = hrs + (mins-mins%60)/60;
mins = mins%60;
document.getElementById('totalHoursv').value = hrs;
document.getElementById('totalMins').value = mins;
}
In onblur event call calculateAllocation() for both hours and minute input field
Demo:
https://jsfiddle.net/kLurp45y/19/

Related

Countdown inside laravel blade

Hi guys, I'm trying to look for a way on how to make the Time Left column count down. I was guessing on doing it via ajax and updating it every minute but I guess it will affect the performance. What is the best way to achieve this? I need it to show the real-time time left of the column also updating the values in the database. Thank you!
You do not to update the time left everytime in the database, I don't think you need to even store it. You need to store the deadline (The End Date) and then the count down will be only on the client side using JavaScript as follows:
let timer = function (date) {
let timer = Math.round(new Date(date).getTime()/1000) - Math.round(new Date().getTime()/1000);
let minutes, seconds;
setInterval(function () {
if (--timer < 0) {
timer = 0;
}
days = parseInt(timer / 60 / 60 / 24, 10);
hours = parseInt((timer / 60 / 60) % 24, 10);
minutes = parseInt((timer / 60) % 60, 10);
seconds = parseInt(timer % 60, 10);
days = days < 10 ? "0" + days : days;
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
document.getElementById('cd-days').innerHTML = days;
document.getElementById('cd-hours').innerHTML = hours;
document.getElementById('cd-minutes').innerHTML = minutes;
document.getElementById('cd-seconds').innerHTML = seconds;
}, 1000);
}
//using the function
const today = new Date()
const tomorrow = new Date(today)
tomorrow.setDate(tomorrow.getDate() + 1)
timer(tomorrow);
<span id="cd-days">00</span> Days
<span id="cd-hours">00</span> Hours
<span id="cd-minutes">00</span> Minutes
<span id="cd-seconds">00</span> Seconds

How to do Countdown algorithm

I am new to programming, and on our programming class, we were asked to do an algorithm that counts the day before Christmas given a date. I have already an algorithm in mind, but it needs defining the number of days there are before Christmas for each month, then a lot of if-else statements. I was just wondering if there is another more efficient algorithm to this problem. I am writing this in pseudocode.
This is what I have done so far:
define jan=359, feb=328, mar=306, apr=269, may=239, jun=208, jul=178, aug=147, sep=116, oct=86, nov=55, dec=25
input mm
input dd
if mm is jan
days= jan - dd
...
This is a countdown function,
let dayMilli = (24*60*60*1000);
let hourMilli = (60*60*1000);
let minuteMilli = (60*1000);
let secondMilli = (1000);
function printTime(millis){
var days = millis/dayMilli;
var lessDay = millis % dayMilli;
var hours = lessDay/hourMilli;
var lessHour = lessDay % hourMilli;
var minute = lessHour/minuteMilli;
var lessMinute = lessHour % minuteMilli;
var second = lessMinute / secondMilli;
$("#myTime").text(parseInt(days) + " Days " + parseInt(hours) + " Hours " + parseInt(minute) + " Minutes " + parseInt(second) + " Seconds");
}
and if you need a countdown for every second you can try
//call every seconds the function update
var myVar = setInterval(update, 1000);
//date of christmas
var christmas = new Date(2018, 12, 25, 0, 0, 0, 0)
//update time difference
function update(){
printTime(getTimeDif(christmas));
}
//get milliseconds difference from today to christmas
function getTimeDif(dateBefore){
return (dateBefore.getTime()- new Date()).getTime());
}

Javascripts - Auto refresh with random number

I want to generate random number for refresh page
How to set math.random between 20 sec until 50 sec?
My Javascript code looks like this:
var number = Math.random() * 50;
var sec = number - (number % 1) + 20;
var url = "http://example.org";
if (sec == 20 || sec == 30 || sec == 40 || sec == 50)
{
setTimeout(function() { window.location = url } , sec * 1000 );
}
Based on this a suggest following statement:
var sec = Math.floor(Math.random() * (50 - 20) + 20);
I tested it with following script:
<script>
a = 20;
b = 50;
for (i = 0; i < 20; i++)
{
alert(Math.floor(Math.random() * (b - a) + a));
}
</script>
and it has never generated a number lower than 20 and higher than 50.

LINQ Query to Find the Maximum Mean for a Time Span

I have a set of data that has two points; "watts" and a time stamp.
Each data point is separated by 1 second.
So it looks like this:
0:01 100
0:02 110
0:03 133
0:04 280
.....
The data set is a couple hours long.
I'd like to write a query where I can find the maximum average watts for different time periods (5 seconds, 1 minutes, 5 minutes, 20 minutes, ect).
I'd also like to know where in the data set that maximum average took place.
Edit
I think I need to do a query with a moving average and the appropriate bucket (let's say 10 seconds). Once I get that result, I query that to find the max.
Try this (I used Linqpad, C# statements):
var rnd = new Random();
// Create some data.
var tw = Enumerable.Range(0, 3600)
.Select(i => Tuple.Create(new TimeSpan(0, 0, i), rnd.Next(1000))).ToList();
// The query.
int secondsPerInterval = 10;
var averages =
tw.GroupBy(t => (int) (t.Item1.TotalSeconds/secondsPerInterval) + 1)
.Select(g => new
{
Seconds = g.Key * secondsPerInterval,
Avg = g.Average(t => t.Item2)
})
.ToList();
var max = averages.Where(tmp => tmp.Avg == averages.Max(tmp1 => tmp1.Avg));
max.Dump();
The trick is to group your timespans by the integral part of TotalSeconds divided by the required interval length.
You could do tw.AsParallel().GroupBy..., but you should benchmark if you loose more by parallellization overhead than you gain.
Okay, a guy at work helped me. Here's the answer in LINQ Pad.
var period = 10;
var rnd = new Random();
// Create some data.
var series = Enumerable.Range(0, 3600)
.Select(i => Tuple.Create(new TimeSpan(0, 0, i), rnd.Next(300))).ToList();
var item = Enumerable.Range(0, 3600).AsParallel()
.Select(i => series.Skip(i).Take(10))
.Select((e, i) => new { Average = e.Sum(x => x.Item2) / e.Count(), Second = i })
.OrderByDescending(a => a.Second).Dump();
item.First().Dump();
try this (untested):
for (int i = 0; i < = dataList.count ; i = i + (TimePeriod))
(from p in dataList.Skip(i).Take(TimePeriod) select p).Average(s => s.Watts)

calculate elapsed time in flash

I am building a quiz and i need to calculate the total time taken to do the quiz.
and i need to display the time taken in HH::MM::SS..any pointers?
new Date().time returns the time in milliseconds.
var nStart:Number = new Date().time;
// Some time passes
var nMillisElapsed:Number = new Date().time - nStart;
var strTime:String = Math.floor(nMillisElapsed / (1000 * 60 * 60)) + "::" +
(Math.floor(nMillisElapsed / (1000 * 60)) % 60) + "::" +
(Math.floor(nMillisElapsed / (1000)) % 60);
I resurrect this question to say that both Brian and mica are wrong. Creating a new Date() gives you the time according to the computer's clock. All someone has to do is set their clock back several minutes, and that would cause the quiz timer to go back several minutes as well. Or worse, they could set their clock back to a time before they started the quiz, and your app would think they spent a negative amount of time taking the quiz. o.O
The solution is to use flash.utils.getTimer(). It returns the number of milliseconds since the swf started playing, regardless of what the computer's clock says.
Here's an example:
var startTime:Number = getTimer();
// then after some time passes:
var elapsedMilliseconds:Number = getTimer() - startTime;
Then you can use Brian's code to format the time for display:
var strTime:String = Math.floor(elapsedMilliseconds / (1000 * 60 * 60)) + "::" +
(Math.floor(elapsedMilliseconds / (1000 * 60)) % 60) + "::" +
(Math.floor(elapsedMilliseconds / (1000)) % 60);
Fill with zero when number is less than 10 (Thanks brian)
var now:Date; //
var startDate:Date;
var startTime:Number;
// initialize timer and start it
function initTimer():void{
startDate = new Date();
startTime = startDate.getTime();
//
var timer:Timer = new Timer(1000,0); // set a new break
timer.addEventListener(TimerEvent.TIMER, onTimer); // add timer listener
//
function onTimer():void{
now=new Date();
var nowTime:Number = now.getTime();
var diff:Number = nowTime-startTime;
var strTime:String = Math.floor(diff / (1000 * 60 * 60)) + ":" +
zeroFill(Math.floor(diff / (1000 * 60)) % 60) + ":" +
zeroFill(Math.floor(diff / (1000)) % 60);
// display where you want
trace('time elapsed : ' + strTime);
}
// fill with zero when number is less than 10
function zeroFill(myNumber:Number):String{
var zeroFilledNumber:String=myNumber.toString();
if(myNumber<10){
zeroFilledNumber = '0'+zeroFilledNumber;
}
return zeroFilledNumber;
}
// start TIMER
timer.start();
}
initTimer();
var countdown:Timer = new Timer(1000);
countdown.addEventListener(TimerEvent.TIMER, timerHandler);
countdown.start();
function timerHandler(e:TimerEvent):void
{
var minute = Math.floor(countdown.currentCount / 60);
if(minute < 10)
minute = '0'+minute;
var second = countdown.currentCount % 60;
if(second < 10)
second = '0'+second;
var timeElapsed = minute +':'+second;
trace(timeElapsed);
}

Resources