Subtracting Time In Javascript [duplicate] - javascript

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);

Related

Formatting MomentJS duration above 24 hours

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);
},

How to compare two time values by pure JavaScript? [duplicate]

This question already has answers here:
Check time difference in Javascript
(19 answers)
Closed 5 years ago.
I try compare two different time to produce the difference time.
var start_time;
var end_time;
start_time = $('#startTime').val();
end_time = $('#endTime').val();
values received are,
start_time : 5:08 PM
end_time : 6:08 PM
here, how can get a difference time as 1 hr from these time ?
Expected output: 01:00
Is this possible with JavaScript ?
Hope this snippet will be useful
function getDifference(t1, t2) {
//first splitting by white space. FOr example 5:08 PM will be 5:08 and again splitting by :
var _t1 = (t1.split(" ")[0].split(":")),
// converting to number to get the time in minute
toNum1 = Number(_t1[0]) * 60 + Number(_t1[1]),
_t2 = (t2.split(" ")[0].split(":")),
toNum2 = Number(_t2[0]) * 60 + Number(_t2[1]),
// calulating difference
dif = toNum2 - toNum1;
var result = ''
if (dif % 60 === 0) {
result = dif % 60 + ':00'
} else if (dif % 60 < 10) {
result = Math.floor(dif / 60) + ':0' + dif % 60
} else if (dif % 60 > 10) {
result = Math.floor(dif / 60) + ':' + dif % 60
}
return result
}
console.log(getDifference("5:08 PM", "6:59 PM"))
Filter to time string part, parse to numbers, compensate for AM/PM (why not just use 24 hours model?) and return array of differences.
/**
* Takes time as "... Hours:Minutes ..." and returns array of integers "[hours, minutes]"
*
* #param {string} time
* #returns
*/
function splitTime(time) {
return /\d{1,2}:\d{1,2}/ig
.exec(time)
.pop()
.split(":")
.map(function(a) {
return parseInt(a, 10);
});
}
function timeDifference(from, to) {
var t1 = splitTime(from);
var t2 = splitTime(to);
if (from.toLowerCase().indexOf("pm") >= 0) {
t1[0] = t1[0] + 12;
}
if (to.toLowerCase().indexOf("pm") >= 0) {
t2[0] = t2[0] + 12;
}
var diff = [t2[0] - t1[0], t2[1] - t1[1]];
return diff;
}
console.log("Raw return:", timeDifference("5:08 AM", "6:08 AM"));
console.log("Formatting return:", timeDifference("5:08 AM", "6:08 AM").join(":"));
var start_time = "5:08 PM"
var end_time = "6:10 PM"
var d1 = Date.parse('1/1/2000 '+start_time)
var d2 = Date.parse('1/1/2000 '+end_time)
var diff = (d2-d1)/(60*1000)
var h = Math.floor(diff/60)
var m = diff-h*60
var result = h+":"+("00"+m).slice(-2)
document.write(result)
You can use pure javascript but moment will be better. A not ended example would be something like that:
var date1 = new Date();
date1.setHours('5:08 PM'.split(':')[0]); //Not checking PM or AM
date1.setMinutes( ....
return (Math.abs(date1.getTime()-date2.getTime()) / (1000*60*60)) % 24 //returning only hours you will need to add seconds

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

Convert hundredths to “minutes:seconds.hundredths” in javascript

In Javascript, I need help to convert an integer with hundredths to "minutes:seconds.hundredths".
So for example, I have this: '10420' and want to display it like this: 01:44.20.
Any Ideas?
function leading0(number){ return number < 10 ? "0" : "";}
mins = parseInt((hundredths / 100) / 60)
secs = parseInt((hundredths / 100) % 60)
huns = parseInt(hundredths % 100)
output = leading0(mins) + mins + ":" + leading0(secs) + secs + "." + leading0(huns) + huns;
jsFiddle example: http://jsfiddle.net/cNu2t/
var hundredths = 10420;
var seconds = Math.floor(hundredths / 100);
var minutes = Math.floor(seconds / 60);
return minutes+":"+(seconds-minutes*60)+"."+("0"+(hundredths-seconds*100)).substr(-2);
or:
function leadingZero(n) { return ("00"+n).substr(-2); }
var hundredths = 10420;
var secs = ~~(hundreths/100);
var mins = ~~(secs/60);
return mins+":"+leadingZero(secs%60)+"."+leadingZero(hundredths%100);
Moment.js should be able to handle this based on it's pretty rich set of formatting, parsing, etc. that it offers. I don't know if you'll be doing enough additional date and/or time related stuff to make adding a 5K JavaScript library to the set of resources you download for a page, but it might be worth a look if you have other spots where you could put it to use.
I know it deals in milliseconds and you can just multiply your number by ten to get to milliseconds and then pass it through their formatting function to output what you're after I think.

How to get of two time values using jQuery/Javascript?

I have two values that are used for the amount of time it will take to complete a task. How can I add these values together to come up with a total number of hours and minutes, but still have the value account for 60 minutes equalling one hour?
The two values I'd like to get the sum of and the total value are in HH:MM (00:00) format.
Thanks!
Writing your own time and date functions can get complex. Why re-invent the wheel. Take a look at the excellent http://www.datejs.com/ date library. It handles all date and time related tasks and usage is very simple.
Here's something I had laying around. It allows for an infinite number of arguments, so you could have addTime('01:00') or addTime('01:00', '02:00', '03:00', '04:00'), etc. It's three functions long because it also verifies if the times entered are properly formatted, and if not, then it formats them. (E.g. Ensures that minutes is 2 digits long, and if hours is 1 digit long, then pad it with one zero, etc.)
You can play with it here: http://jsfiddle.net/WyxwU/
It's also here:
var totalTime = addTime('12:34', '56:12', '78:45');
document.write(totalTime);
function addTime()
{
if (arguments.length < 2)
{
if (arguments.length == 1 && isFormattedDate(arguments[0])) return arguments[0];
else return false;
}
var time1Split, time2Split, totalHours, totalMinutes;
if (isFormattedDate(arguments[0])) var totalTime = arguments[0];
else return false;
for (var i = 1; i < arguments.length; i++)
{
// Add them up
time1Split = totalTime.split(':');
time2Split = arguments[i].split(':');
totalHours = parseInt(time1Split[0]) + parseInt(time2Split[0]);
totalMinutes = parseInt(time1Split[1]) + parseInt(time2Split[1]);
// If total minutes is more than 59, then convert to hours and minutes
if (totalMinutes > 59)
{
totalHours += Math.floor(totalMinutes / 60);
totalMinutes = totalMinutes % 60;
}
totalTime = totalHours + ':' + padWithZeros(totalMinutes);
}
return totalTime;
}
function isFormattedDate(date)
{
var splitDate = date.split(':');
if (splitDate.length == 2 && (parseInt(splitDate[0]) + '').length <= 2 && (parseInt(splitDate[1]) + '').length <= 2) return true;
else return false;
}
function padWithZeros(number)
{
var lengthOfNumber = (parseInt(number) + '').length;
if (lengthOfNumber == 2) return number;
else if (lengthOfNumber == 1) return '0' + number;
else if (lengthOfNumber == 0) return '00';
else return false;
}
Here is the simple JS code for this,
var a = "2:50";
var b = "2:15";
var splitTimeStr = function(t){
var t = t.split(":");
t[0] = Number(t[0]);
t[1] = Number(t[1]);
return t;
};
var addTime = function(t1, t2){
var t1Hr = splitTimeStr(t1)[0];
var t1Min = splitTimeStr(t1)[1];
var t2Hr = splitTimeStr(t2)[0];
var t2Min = splitTimeStr(t2)[1];
var rHr = t1Hr + t2Hr;
var rMin = t1Min + t2Min;
if (rMin >= 60)
{
rMin = rMin - 60;
rHr = rHr + 1;
}
if (rMin < 10) rMin = "0" + rMin;
if (rHr < 10) rHr = "0" + rHr;
return "" + rHr + ":" + rMin;
};
document.write(addTime(a, b));
you can validate/play this with code here: http://jsfiddle.net/z24v7/
What you have to do is calculate them to a decimal by that I mean.
Strip out the hour/mins multiple that by 60 + to mins
//strip out the hours
l_hour = Number(l_time$.substr(0, l_pos));
//Strip out the mins
l_min = Number(l_time$.substr(l_pos + 1, l_time$.length));
//add the two values divided by 60 mins
l_time_decimal= Number(Math.abs(l_hour)) + Number(Math.abs(l_min)/60);
Do this for each value then deduct the two figures to give you the difference (i.e time taken). All thats left is convert it back from a decimal to a time
l_difference_in_min = l_difference * 60;
l_time_mins = l_difference_in_min%60;
l_time_hours = (l_difference_in_min - l_mins)/60;
Now just format the two to be HH:MM
I would break the problem into sub-tasks that are reusable. You have to concerns here:
Process a time string in "hh:mm" format: Converting this to minutes makes sense because it seems to be the time granularity at which you're operating.
Format a given number of minutes into a time string in "hh:mm" format.
The fact that you're adding two times together is a diversion from the actual two problems above.
Parse a time string into minutes:
function parseMinutes(s) {
var tokens = s.split(":");
return tokens[0] * 60 + parseInt(tokens[1]);
}
Format minutes into a time string:
function formatMinutes(minutes) {
function pad(n) {
return n > 9
? n
: ("0" + n);
}
var hours = Math.floor(minutes / 60),
mins = minutes % 60;
return pad(hours) + ":" + pad(mins);
}
Then your specific problem can be tackled by:
var sum = formatMinutes(parseMinutes(a) + parseMinutes(b));

Categories