Sum of to times using javascript - javascript

can anyone tell me how to do sum of two time using javascript (momentjs) for exemple the sum of:
2:44:56 and 2:50:56
i tried that but doesnt work:
2:44:56 + 2:50:56
any suggestions please??

Momentjs has a duration object that can be used to add or subtract two or more timespans.
const a = moment.duration('02:44:56');
const b = moment.duration('02:50:56');
const c = a.add(b);
console.log(c.hours() );
console.log(c.minutes() );
console.log(c.seconds() );

One could add the seconds, then calculate the carry value and add that to the sum of minutes and so on. That can be easily done with reduce:
function sum(date1, date2){
date1 = date1.split(":");
date2 = date2.split(":");
const result = [];
date1.reduceRight((carry,num, index) => {
const max = [24,60,60][index];
const add = +date2[index];
result.unshift( (+num+add+carry) % max );
return Math.floor( (+num + add + carry) / max );
},0);
return result.join(":");
}
console.log(
sum("2:44:56" , "2:50:56" )
);
Try it

You can do it like this. Use add method on moment object and pass your data.
let x = moment({
hours:'2',
minutes:'44',
seconds:'56'})
.add({
hours:'2',
minutes:'50',
seconds:'56' })
console.log(x)
or dynamically pass data
let time = {
hours: 2,
minutes:44,
seconds: 56
}
let time2 = {
hours: 2,
minutes:50,
seconds: 56
}
let y = moment(time)
.add(time2)
console.log(y)

The code:
var t1 = moment('2:44:56', 'HH:mm:ss');
var t2 = '2:50:56';
var parsed_t2 = t2.split(':') // [2, 50, 56]
var r = t1.add({
hours: parsed_t2[0], // 2
minutes: parsed_t2[1], // 50
seconds: parsed_t2[2], // 56
});
The process:
Parse the string as a moment object (helping it with defining the format we're using;
Split the time we want to add to the t1 by using the split() function effectively splitting our t2 into an array where we have [hours, minutes, seconds]
Add the the times together using the moments add() method.
Working example

moment() function takes hours, minutes, seconds as arguments and return a moment object which has a add() method that also can take hours, minutes, seconds as arguments and return total times.
Try addTimes(time1, time2)
function addTimes(time1, time2) {
let [hours1, minutes1, seconds1] = time1.split(':');
let [hours2, minutes2, seconds2] = time2.split(':');
return moment({ hours: hours1, minutes: minutes1, seconds: seconds1 })
.add({ hours: hours2, minutes: minutes2, seconds: seconds2 })
.format('h:mm:ss');
}
console.log(addTimes('2:44:56', '2:50:56'));

Good old JS solution:
var base = new Date(0);
var t1 = new Date(base);
var t2 = new Date(base);
t1.setUTCHours(2,45,50);
t2.setUTCHours(2,50,50);
var t = new Date(t1.getTime() + t2.getTime() - base.getTime());
result = t.getUTCHours() + ":" + t.getUTCMinutes() +":" + t.getUTCSeconds();
console.log(result);
Note that JS automatically converts time of the day to GMT timezone hence we need to use UTC version of time functions.

Related

Convert string to time and add 2 hours in JS

i get this time from an external JSON :
"time":"19:45"
I need to add 2 hours from this string.
Is it possible in JS?
Thanks
Try this
let myTime = '19:45'
function getTime(time, addHour) {
let [h, m] = time.split(':');
let date = new Date();
date.setHours(h, m, 0)
date.toString();
let res = `${date.getHours()+addHour}:${date.getMinutes()}`
return res
}
console.log(getTime( myTime, 2 ))
uses String.split to get hourNum and minuteNum, then construct one Date object and uses setTime to add two hours.
function addHours(text, hours=2) {
const [hourNum, minNum] = text.split(':')
const time = new Date(0, 0, 0, hourNum, minNum)
time.setTime(time.getTime() + (hours * 60 * 60 * 1000))
return `${time.getHours()}:${time.getMinutes()}`
}
console.log(addHours('19:45', 2))
console.log(addHours('23:45', 2))
A Date object isn't necessary to do time mathematics, it just means taking account of minutes and seconds (60) and maybe days (24).
E.g.
// Add time to a timestamp, both in in HH:mm format
// If respectDay is true, hours are % 24
function addTime(start, increment, respectDay = false) {
let pad = n => ('0' + n).slice(-2);
let timeToMins = time => time.split(':').reduce((h, m) => h*60 + m*1);
let minsToTime = (mins, respectDay = false) => `${pad((mins / 60 | 0) % (respectDay? 24 : Number.POSITIVE_INFINITY))}:${pad(mins%60)}`;
return minsToTime(timeToMins(start) + timeToMins(increment), respectDay);
}
let time = "19:45";
console.log(addTime(time, '8:23')); // Total time : 28:08
console.log(addTime(time, '8:23', true)); // As day time : 04:08

Calculate duration by start and end hour

I have this json :
{
endTime: "14:00:00"
startTime: "12:00:00"
}
I need to calculate duration, so I did like this :
let duration = endTime.slice(0, -3) - startTime.slice(0, -3);
But not working as expected. I have a js error : left-hand must be type number
Have an idea about that ?
Thx in advance.
Ok, I'm considering you are only receiving an object with endTime and startTime properties and not working with arrays.
In the following code block, you can transform your strings into dates and do calcs with them. In this example, I just subtracted endDate - startDate to get the difference in milliseconds and then I converted to seconds, minutes and hours.
const data = {
endTime: '14:00:00',
startTime: '12:00:00',
}
// separates the string in hours, minutes and seconds
const [startHours, startMinutes, startSeconds] = data.startTime.split(':')
const [endHours, endMinutes, endSeconds] = data.endTime.split(':')
// creates a Date instance to work with
const startDate = new Date()
const endDate = new Date()
// sets hour, minutes and seconds to startDate
startDate.setHours(startHours)
startDate.setMinutes(startMinutes)
startDate.setSeconds(startSeconds)
// sets hour, minutes and seconds to endDate
endDate.setHours(endHours)
endDate.setMinutes(endMinutes)
endDate.setSeconds(endSeconds)
const differenceInMilliseconds = endDate - startDate
const differenceInSeconds = differenceInMilliseconds / 1000
const differenceInMinutes = differenceInSeconds / 60
const differenceInHours = differenceInMinutes / 60
console.log(differenceInHours) // outputs 2 hours
Too many ways to do that, this is one of the simple ways.
Cast the time to a Date object, then get their timestamp (ms), finally get the duration:
const startTimeTs = new Date(`2021-04-01 ${startTime}`).valueOf();
const endTimeTs = new Date(`2021-04-01 ${endTime}`).valueOf();
const durationTs = endTimeTs - startTimeTs;
const durationInSecondes = durationTs / 1000;
const durationInMinutes = durationInSecondes / 60;
const durationInHours = durationInMinutes / 60;
const json = {
endTime: "14:00:00",
startTime: "12:00:00"
};
const start = new Date(2000, 3, 3, ...(json.startTime.split(':').map( x => Number(x))));
const end = new Date(2000, 3, 3, ...(json.endTime.split(':').map( x => Number(x))));
const output = document.getElementById('output');
output.textContent = ((end-start)*0.001)+ ' seconds difference';
<div id="output"></div>
There to many ways to do it, but if you need in same format as you got in json you can use something like it
const data = {
endTime: "14:00:00",
startTime: "12:00:00"
};
const { endTime, startTime } = data;
const endTimeArr = endTime.split(':').map(el => +el);
const startTimeArr = startTime.split(':').map(el => +el);
const resArr = endTimeArr.map((el, i) => el - startTimeArr[i]);
const res = resArr.join(':');
You can do it like this:
let times = {
endTime: "14:00",
startTime: "12:00:00"
};
function calculate(obj) {
let startTime = obj.startTime;
let endTime = obj.endTime;
let sum = new Date(parseInt(endTime)) - new Date(parseInt(startTime));
return sum;
}
console.log(calculate(times));
Convert the HH:MM:SS to seconds.
Subtract the two values - you get the seconds of duration.
Convert the seconds to HH:MM:SS.
/* helper functions */
const format = n =>
String(n).padStart(2, 0);
const time2seconds = time => {
const [hours, minutes, seconds] = time.split(":").map(Number);
return seconds + minutes * 60 + hours * 60 * 60;
}
const seconds2time = seconds => {
const hours = format(Math.floor(seconds / (60 * 60)));
const minutes = format(Math.floor(seconds / 60) % 60);
seconds = format(seconds % 60);
return `${hours}:${minutes}:${seconds}`;
}
/* /helper functions */
const toDuration = ({startTime, endTime}) =>
seconds2time(time2seconds(endTime) - time2seconds(startTime));
test({
endTime: "14:00:00",
startTime: "12:00:00"
})
test({
endTime: "15:30:00",
startTime: "11:00:00"
})
test({
endTime: "18:24:05",
startTime: "11:47:12"
})
function test(obj) {
const result = toDuration(obj);
console.log(`duration between ${obj.startTime} and ${obj.endTime} is: ${result}`);
}

How To Get The Sum of Two Times Using Moment.js?

I want to add two times like time1 = '00:05' and time2 = '10:00'. I want the result like the following after sum: result='10:05'. I used moment for that, this is what I used:
let x = moment.duration(moment(this.time1, "hh:mm A").add(moment(this.time2, "hh:mm A")));
let result = moment.utc(x.asMilliseconds()).format('HH:mm:ss');
but I got nothing, how can I do it?
You can't add time this way with moment because you are asking it to add two times, not a time plus a duration. If you want to add ten minutes, use the add() function with a duration.
moment(this.time2, "hh:mm A").add(10, 'minutes')
More here: https://momentjs.com/docs/#/manipulating/add/
It's not really clear in your question what 00:05 PM means. That doesn't look like a valid time. Moment will interpret it as 12:05pm, but it looks like you want to interpret it as 5 minutes. (That's the only way you get 10:05 as an answer). You can do this with moment if you don't include the PM part of the string.
moment.duration('00:05')
Is a duration of five minutes. You can add this to your time with:
moment('10:00 PM', '"hh:mm A"').add(moment.duration('00:05'))
// 22:05:00
Adding two periods works but it is currently not obvious in moment, how to format it like you want. Until they add format() to durations this will have to do:
var d = moment.duration('03:10:10').add(moment.duration('01:20:30'))
moment.utc(d.as('milliseconds')).format("HH:mm:ss")
// '04:30:40'
See Example For Add & Diff using moment.js .. cheers😀
// addTimes(["01:00", "00:30", "00:50"]) ---- 02:20
addTimes(times) {
let duration = 0;
times.forEach(time => {
duration = duration + moment.duration(time).as('milliseconds')
});
return moment.utc(duration).format("HH:mm")
}
// subtractTimes(["05:00", "00:30", "00:20"]) --- 04:10
subtractTimes(times) {
let totalDiff = 0
for (let i = 0; i < times.length; i++) {
let duration = moment.duration(times[i]).as('milliseconds')
if (i == 0) {
totalDiff = duration
}
if (i > 0) {
totalDiff = totalDiff - duration
}
}
return moment.utc(totalDiff).format("HH:mm")
}
function addTwoHours(firstTime = "20:40", secondTime = "18:40") {
firstTime = firstTime.split(':');
secondTime = secondTime.split(':');
const now = moment();
const expiration = moment().add({ hour: firstTime[0], minute: firstTime[1] }).add({ hour: secondTime[0], minute: secondTime[1] });
const diff = expiration.diff(now);
const diffDuration = moment.duration(diff);
return {
"years": diffDuration.years(),
"months": diffDuration.months(),
"days": diffDuration.days(),
"hours": diffDuration.hours(),
"minutes": diffDuration.minutes(),
"yourAnswer" : `${expiration.diff(now, 'hours')}:${diffDuration.minutes()}`
}
}
console.log(addTwoHours());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

Moment-Range: Need to divide day into 15 minute slices

At present I can only divide the day into 1 hour blocks.
But I need the ranges in 15 minute steps.
Moment-Range Documentation
This is my present code:
function iterateOverDayByIntervalOfHours(inputJSON){
var day = getDayFromFromJSON(inputJSON);
var start = new Date("2016-05-04T00:00:00.000Z");
var end = new Date("2016-05-04T23:59:59.999Z");
var range = moment.range(start, end);
var slices = {}
range.by( 'hours', function(moment) {
console.log(moment);
slices["moment"] = moment
console.log("slices: "+ slices["moment"]);
var ROTsAccumulatedForInterval = getAccumulatedROTForTimeIntervall(range);
var NumberOfFlightsForInterval = getNumberOfFlightsForTimeIntervall(range);
});
console.log(slices["moment"]);
}
any ideas?
Here is another way using moment lib with moment-range extension:
const day_start = moment().startOf('day').hours(7); // 7 am
const day_end = moment().startOf('day').hours(22) // 10 pm
const day = moment.range(day_start, day_end)
const time_slots = Array.from(day.by('minutes', {step: 30}))
in
Array.from(day.by('minutes', {step: 30}))
You can change 'minutes' for hours, days, weeks
and step for how many minutes/hours/days you want to chunk by.
return value will be
[ moment("2017-10-20T07:00:00.000"),
moment("2017-10-20T07:30:00.000"),
moment("2017-10-20T08:00:00.000"),
moment("2017-10-20T08:30:00.000"),
moment("2017-10-20T09:00:00.000"),
moment("2017-10-20T09:30:00.000"),
...
moment("2017-10-20T19:30:00.000"),
moment("2017-10-20T20:00:00.000"),
moment("2017-10-20T20:30:00.000"),
moment("2017-10-20T21:00:00.000"),
moment("2017-10-20T21:30:00.000"),
moment("2017-10-20T22:00:00.000") ]
This doesn't use moment and it's not implemented in your function yet, but this is how I would try to get an object of 15min-chunks. I hope, this is what you are looking for.
var start = new Date("2016-05-04T00:00:00.000Z");
var end = new Date("2016-05-04T23:59:59.999Z");
var slices = {};
var count = 0;
var moment;
while (end >= start) {
start = new Date(start.getTime() + (15 * 60 * 1000));
slices[count] = start;
count++;
}
console.log(slices);
You can also use something like this.
// Take a starting point
const start = moment('00:00:00', 'HH:mm:ss');
// Take a end point
const end = moment('23:59:59', 'HH:mm:ss');
const timeSeries = [];
while (start.isSameOrBefore(end)) {
// add 15 minutes to the starting point
timeSeries.push(start.add(15, 'm').format('HH:mm'));
}
console.log(timeSeries);
Too late but might be helpful, I'm doing the following to divide a day into hour date ranges.
using lodash and moment
const generateDayHours = (x = 24) => {
const hoursArr = [];
_.times(x, (i) => {
hoursArr.push({
fromDate: moment().startOf('day').add(x - (i + 1), 'hour').startOf('hour'),
toDate: moment().startOf('day').add(x - (i + 1), 'hour').endOf('hour')
});
});
return hoursArr;
};
jsbin to test

JAVASCRIPT: subtracting Time and getting its number of minutes

For Example:
StartTime = '00:10';
EndTIme = '01:20';
These variables are string
Question: How can I Subtract them and returning the span time in minutes?
Hope you can help
Make a function to parse a string like that into minutes:
function parseTime(s) {
var c = s.split(':');
return parseInt(c[0]) * 60 + parseInt(c[1]);
}
Now you can parse the strings and just subtract:
var minutes = parseTime(EndTIme) - parseTime(StartTime);
var startTime = "0:10";
var endTime = "1:20";
var s = startTime.split(':');
var e = endTime.split(':');
var end = new Date(0, 0, 0, parseInt(e[1], 10), parseInt(e[0], 10), 0);
var start = new Date(0, 0, 0, parseInt(s[1], 10), parseInt(s[0], 10), 0);
var elapsedMs = end-start;
var elapsedMinutes = elapsedMs / 1000 / 60;
If you're going to be doing a lot of date/time manipulation, it's worth checking out date.js.
However, if you're just trying to solve this one problem, here's an algorithm off the top of my head.
(1)Parse start/end values to get hours and minutes, (2)Convert hours to minutes, (3)Subtract
function DifferenceInMinutes(start, end) {
var totalMinutes = function(value) {
var match = (/(\d{1,2}):(\d{1,2})/g).exec(value);
return (Number(match[1]) * 60) + Number(match[2]);
}
return totalMinutes(end) - totalMinutes(start);
}
dojo.date.difference is built for the task - just ask for a "minute" interval.
Get the difference in a specific unit of time (e.g., number of months, weeks, days, etc.) between two dates, rounded to the nearest integer.
Usage:
var foo: Number (integer)=dojo.date.difference(date1: Date, date2: Date?, interval: String?);

Categories