Formatting MomentJS duration above 24 hours - javascript

I would like to format a summed up total working hours e.g. 49.75 to this: 49:45.
When I use duration like this:
const dur = moment.duration(49.75, 'hours').asMilliseconds();
moment.utc(dur).format("HH:mm:ss") // 01:45:00
I'll receive 01:45:00 instead of 49:45:00
Is there a way to format (instead of HH) duration without dropping the days?

I think you cannot use format but build it manually:
var dur = moment.duration(49.75, 'hours');
var hours = Math.floor(dur.asHours());
var mins = Math.floor(dur.asMinutes()) - hours * 60;
var sec = Math.floor(dur.asSeconds()) - hours * 60 * 60 - mins * 60;
var result = hours + ":" + mins + ":" + ((sec > 9) ? sec : ("0"+sec));
console.log(result); // 49:45:00
Fiddle
Hope someone will find more elegant way

I recommend you this answer.
You can add a format for the duration, and it works for greater than 24 Hour.
function(input) {
input = input || '';
var out = '';
var dur = moment.duration(input, 'minutes');
return dur.format('HH:mm:ss');
};
I hope it can help you!
EDIT:
This code uses duration-format plugin!

If you are modifying one second at a time, it can be simplified quite a lot (parsing and updating).
Inspiration lifted from this answer: https://stackoverflow.com/a/45629433/11121690
incrementTime: (sectionKey, itemKey) => {
const pad = (number) => `${number > 9 ? number : "0" + number}`;
const timeString = STATS_DATA_UTIL.getByParts(sectionKey, itemKey);
const parts = timeString.split(':');
let uiSecs = parseInt(parts[2]);
let uiMins = parseInt(parts[1]);
let uiHrs = parseInt(parts[0]);
uiSecs++;
if (uiSecs === 60) {
uiSecs = 0; uiMins++;
if (uiMins === 60) uiMins = 0; uiHrs++;
}
const result = `${pad(uiHrs)}:${pad(uiMins)}:${pad(uiSecs)}`;
STATS_DATA_UTIL.setByParts(sectionKey, itemKey, result);
},

Related

Subtracting Time In Javascript [duplicate]

I have two time strings like 03:01 and 01:19 . I want to subtract these two,
I tried like below,
var time1= "03:01".split(':');
var time2= "01:19".split(':');
var minutes = Math.abs(Number(time1[1])-Number(time2[1]));
var hours = Math.floor(parseInt(minutes / 60));
hours = Math.abs(Number(time1[0])-Number(time2[0])-hours);
minutes = minutes % 60;
if(hours.toString().length == 1){
hours = '0'+hours;
}
if(minutes.toString().length == 1){
minutes = '0'+minutes;
}
console.log(hours+':'+minutes);
Expected Answer -> 01:42
Actual Answer -> 02:18
Can someone tell me,where I am doing wrong ?
Using a couple of utility functions like below might help.
Basically strToMins convert string to minutes.
and minsToStr to convert back to a string.
Example below.
var time1= "03:01";
var time2= "01:19";
function strToMins(t) {
var s = t.split(":");
return Number(s[0]) * 60 + Number(s[1]);
}
function minsToStr(t) {
return Math.trunc(t / 60)+':'+('00' + t % 60).slice(-2);
}
var result = minsToStr( strToMins(time1) - strToMins(time2) );
console.log(result);

DOM Elements Convert to Integer and converting them into a total time amount - Hour / Minutes parseFloat

So I have a website logged idea and I am trying to get all the minutes & hours and then create total time.
Here is the site:
https://e013g.csb.app/
and here is the codesand box:
https://codesandbox.io/s/boring-lalande-e013g?file=/src/index.js
As you can see I get the minutes and try to convert it to parseFloat and then try and it all up but there is where I am stuck.
const mins = document.querySelectorAll('.minutes');
// console.log(mins.value.innerText);
//var totalMinutes = 0;
mins.forEach(min => {
const convertMins = parseFloat(min.innerHTML);
// console.log(`convertMins: ${convertMins}`);
const calculate = min + convertMins;
//const calculate = convertMins + convertMins;
console.log(calculate);
// const minutes = min.innerHTML;
// console.log(`Minutes: ${minutes}`);
//console.log(min.innerText);
});
If anyone could offer guidance I would be really grateful.
Thank you,
Dave.
P.S I have asked on Reddit here too: https://www.reddit.com/r/learnjavascript/comments/hlktfs/getting_all_minutes_and_hours_and_converting_them/
Thank you!
EDIT
Thank you to Pedro for the assistance here is the whole solution should anyone want to do this:
//Minutes
const mins = document.querySelectorAll(".minutes");
var totalMinutes = 0;
mins.forEach(min => {
const convertMins = parseFloat(min.innerHTML);
totalMinutes = totalMinutes + convertMins;
});
console.log(totalMinutes);
//Hours
const hours = document.querySelectorAll(".hours");
var totalHours = 0;
hours.forEach(hour => {
const convertHours = parseFloat(hour.innerHTML);
console.log(`Hours: ${convertHours}`);
const newMins = convertHours * 60;
console.log(`new mins: ${newMins}`);
// totalHours = totalHours + convertHours;
totalHours = totalHours + newMins;
});
console.log(`Total Hours ${totalHours}`);
//Then add the lot
const addTotal = totalMinutes + totalHours;
console.log(`This is the total time: ${addTotal}`);
//Then Convert The Lot
function time_convert(addTotal) {
var hours = Math.floor(addTotal / 60);
var minutes = addTotal % 60;
return `${hours} hrs : ${minutes} Minutes`;
}
// console.log(time_convert(161));
const headingTotal = document.querySelector(".totalTime");
console.log(headingTotal);
headingTotal.innerText = time_convert(addTotal);
The shortest way is using reduce:
const mins = document.querySelectorAll('.minutes');
var totalMinutes = mins.reduce((sum, min) => {
const convertMins = parseFloat(min.innerHTML);
return sum + convertMins;
}, 0);
console.log(totalMinutes);
But in case this is complicated for you, here is a solution using forEach:
const mins = document.querySelectorAll('.minutes');
var totalMinutes = 0;
mins.forEach(min => {
const convertMins = parseFloat(min.innerHTML);
totalMinutes = totalMinutes + convertMins;
});
console.log(totalMinutes);

How do I use setInterval with my form to create an alarm clock?

I'm currently trying to learn JavaScript and I've decided to make things more interesting by actually creating something instead of endless reading & no practice. I'm currently trying to build an alarm clock.
Here's my code:
http://codepen.io/anon/pen/dCsax
function wakeup() {
window.location = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
}
I need to create another function that uses setInterval to check every few seconds if the time set in that form is equal to the current time, and if it is, execute the wakeup function that plays Rick Astley - Never Gonna Give You Up.
I don't know how to write this piece of code. Could someone please help me out so I can see how it's done?
Thanks in advance.
For a pure JS solution (no libraries) you should read about Date object
I've forked your example on codepen like this:
function set_alarm() {
var h = document.getElementById('h').value;
var m = document.getElementById('m').value;
var t = document.getElementById('t').value;
if ( t == 'PM' ) h+= 12;
var now = new Date();
var d = new Date();
d.setHours(h);
d.setMinutes(m);
d.setSeconds(0);
var delta = d.getTime() - now.getTime();
if (delta < 0) delta = -delta;
setTimeout(wakeup,delta);
}
This should give you a hint about what to do.
You can also try using one of the many libraries about dates, expecially moment.js
I added an id to your button, and on click set up the timer function as below:
<input id="scheduleTimer" type="button" value="Schedule alarm"></input>
function getTimeoutSec() {
var dt = new Date();
var currSecs = dt.getSeconds() + (60 * dt.getMinutes()) + (60 * 60 * dt.getHours());
var am_pm = document.getElementById('t').value;
var formHour = parseInt(document.getElementById('h').value);
if(am_pm == 'PM') {
formHour += 12;
}
var formMin = parseInt(document.getElementById('m').value);
var formSeconds = (formHour * 3600) + (formMin * 60);
return formSeconds - currSecs;
}
window.onload = function() {
var scheduleTimerButton = document.getElementById('scheduleTimer');
scheduleTimerButton.addEventListener('click', function() {
var secRemaining = getTimeoutSec();
setTimeout(wakeup, secRemaining * 1000);
}, false);
};
Link to CodePen
Here is an example function
function scheduleAlarm() {
var h = document.getElementById('h').value;
var m = document.getElementById('m').value;
var t = document.getElementById('t').value;
alert("Successfully scheduled alram!");
setInterval(function(){
var date = new Date;
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
if (h == hours && m == minutes && t == ampm){
alert("Time to go to school, wake up!")
}
}, 5000); // will run every 5 seconds
}
Demo: CodePen

how to convert the minutes into hours and minutes with subtracted time(subtracted time values)

I want to subtract the two different 24 hours time format.
I had tried with following :
var startingTimeValue = 04:40;
var endTimeValue = 00:55;
var hour = startingTimeValue.split(":");
var hour1 = endTimeValue.split(":");
var th = 1 * hour[0] - 1 * hour1[0];
var tm = 1 * hour[1] - 1 * hour1[1];
var time = th+":"+tm;
This code is working fine if second minutes is not greater than the first.but other case it will return minus values.
The above code sample values result :
time1 : 04:40
time2 : 00:55
The result should be : 03:45 (h:mi) format.
But right now I am getting 04:-5 with minus value.
I had tried with the link as : subtract minutes from calculated time javascript but this is not working with 00:00 format.
So how to calculate the result value and convert into hours and minutes?
I would try something like the following.
The way I see it, it is always better to break it down to a common unit and then do simple math.
function diffHours (h1, h2) {
/* Converts "hh:mm" format to a total in minutes */
function toMinutes (hh) {
hh = hh.split(':');
return (parseInt(hh[0], 10) * 60) + parseInt(hh[1], 10);
}
/* Converts total in minutes to "hh:mm" format */
function toText (m) {
var minutes = m % 60;
var hours = Math.floor(m / 60);
minutes = (minutes < 10 ? '0' : '') + minutes;
hours = (hours < 10 ? '0' : '') + hours;
return hours + ':' + minutes;
}
h1 = toMinutes(h1);
h2 = toMinutes(h2);
var diff = h2 - h1;
return toText(diff);
}
Try:
var time1 = Date.UTC(0,0,0,4,40,0);
var time2 = Date.UTC(0,0,0,0,55,0);
var subtractedValue = time1 - time2;
var timeResult = new Date(subtractedValue);
console.log(timeResult.getUTCHours() + ":" + timeResult.getUTCMinutes());
DEMO
This solution utilizes javascript built-in date. How it works:
var time1 = Date.UTC(0,0,0,4,40,0);
var time2 = Date.UTC(0,0,0,0,55,0);
time1, time2 is the number of miliseconds since 01/01/1970 00:00:00 UTC.
var subtractedValue = time1 - time2;
subtractedValue is the difference in miliseconds.
var timeResult = new Date(subtractedValue);
console.log(timeResult.getUTCHours() + ":" + timeResult.getUTCMinutes());
These lines reconstruct a date object to get hours and minutes.
This works better , A fiddle I just found
var difference = Math.abs(toSeconds(a) - toSeconds(b));
fiddle
This method may work for you:
function timeDiff(s,e){
var startTime = new Date("1/1/1900 " + s);
var endTime = new Date("1/1/1900 " + e);
var diff = startTime - endTime;
var result = new Date(diff);
var h = result.getUTCHours();
var m = result.getUTCMinutes();
return (h<=9 ? '0' + h : h) + ':' + (m <= 9 ? '0' + m : m);
}
var startingTimeValue = "04:40";
var endTimeValue = "00:55";
var formattedDifference = timeDiff(startingTimeValue,endTimeValue);
Demo: http://jsfiddle.net/zRVSg/

Calculate mm:ss + mm:ss

I'm looking for js that does something similar to this: http://www.unitarium.com/time-calculator.
My song-lengths are in an array, not in form fields. And the result have to display hh:mm:ss when needed (or always).
This is the page I want to use this on: http://flamencopeko.net/songs.php.
Make a function to convert the format mm:ss to seconds, and one to convert seconds to the format hh:mm:ss, convert all values to seconds, add them together, and format the result:
function parseMS(s) {
var parts = s.split(':');
return parseInt(parts[0], 10) * 60 + parseInt(parts[1], 10);
}
function formatTwo(n) {
return (n < 10 ? '0' : '') + n.toString();
}
function formatHMS(s) {
var m = Math.floor(s / 60);
s %= 60;
var h = Math.floor(m / 60);
m %= 60;
return formatTwo(h) + ':' + formatTwo(m) + ':' + formatTwo(s);
}
var times = ['14:23', '11:08', '18:59'];
var sum = 0;
for (var i = 0; i < times.length; i++) sum += parseMS(times[i]);
var result = formatHMS(sum);
alert(result);
Demo: http://jsfiddle.net/u6B4g/
I was able to use this PHP:
$str_time = "2:50";
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;
from Convert time in HH:MM:SS format to seconds only? to make bars for my song-lengths here: http://flamencopeko.net/songs.php.
I'll try to use that to get total playing time now.
I think array_sum() is the way to go, but I don't know how.
Up to date source: http://flamencopeko.net/covers.txt.

Categories