0

I have a Check-In app that when the button to Check In is clicked, it fetches an API and returns me the current date and time (2023-01-12T12:59:49.090Z). You can then click it again later but for Check Out. What I'm trying to do now is subtract one from the other as to calculate the total hours worked per employee.

I've tried a bunch of different methods but here's what its looking like:


function renderTable(data) {
    const tbCheckins = document.getElementById('tbCheckins')
    tbCheckins.innerHTML = ""

    data.forEach(function(item) {
        console.log('Item:', item)
        const rowElement = document.createElement(`tr`)
        
        createRowCell(rowElement, new Date(item.checkin_time).toLocaleTimeString())
        const checkoutValue = item.checkout_time == null ? "----" :  new Date(item.checkout_time).toLocaleTimeString()
        
        createRowCell(rowElement,checkoutValue)
        createRowCell(rowElement, calcTotalHours())
        createRowButtons(rowElement, item.id)

        tbCheckins.appendChild(rowElement)
    });
}

function calcTotalHours(){
   var checkOutTime = new Date(item.checkout_time) 
   var checkInTime = new Date(item.checkin_time)}
   var diffHours = Math.abs (checkOutTime - checkInTime)
  
   days = diffHours/(1000 * 3600 * 24)

It is saying that checkOutTime and checkInTime are declared but are not being read.

maj1n
  • 1
  • 2
  • 4
    Does this answer your question? [How do I get the difference between two Dates in JavaScript?](https://stackoverflow.com/questions/41948/how-do-i-get-the-difference-between-two-dates-in-javascript) – Shivangam Soni Jan 12 '23 at 13:38

1 Answers1

0

You need to pass the variable item to the function calcTotalHours()

createRowCell(rowElement, calcTotalHours(item))

and redefine the function as

function calcTotalHours(item){
   var checkOutTime = new Date(item.checkout_time) 
   var checkInTime = new Date(item.checkin_time)}
   var diffHours = Math.abs (checkOutTime - checkInTime)
  
   days = diffHours/(1000 * 3600 * 24)
   return diffHours // this line was not in your example but I assume it should be
}

Otherwise the variable item will be undefined inside calcTotalHours()

ACarter
  • 5,688
  • 9
  • 39
  • 56