简体   繁体   中英

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(':');
  1. Convert the HH:MM:SS to seconds.
  2. Subtract the two values - you get the seconds of duration.
  3. 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}`); }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM