Code for the time difference in hours in a time picker

Hello, I’m new to coding, and I’m stuck when trying to find the time difference (between the current time and the userinput in a time picker). Specifically, I want when a user changes the time in a time picker, the difference in hours between the time chosen and the current time to be displayed in an input box. I’ve tried different code variations, but I don’t know what I’m doing wrong. I would really appreciate some guidance in the right direction.
N/B- the time picker is set to display the current time in 24hr format.
Below is a code snippet that, of course, is not working.

$w.onReady(() =>{
$w("#timePicker1").onChange(() =>{
var today= new Date();
let inputtime = $w("#timePicker1").value;//Value from time picker
let timeDiff = inputtime.getTime()-today.getTime()
let timeDiffhrs = timeDiff/3600000
$w("#input3").value = timeDiffhrs

Maybe this post will help you understanding DATES & TIMES better…

I have worked out the code below but now its resulting to a ‘NaN’ error. Would you help me identify the source of the error or why the code is not working?

$w.onReady(() =>{
$w("#timePicker1").onChange(() =>{
var today= new Date();
let inputtime = $w("#timePicker1").value;//Value from time picker
$w("#input3").value =`${Number(inputtime.getHour -String(today.getHour))} hrs left`
});
})

I will keep your post in mind.
Will answer tomorrow.

…to be continued…

You can generate a function, which would add time to an existing date.

For example…


$w.onReady(async() =>{
    let myDate= addHoursToDate(new Date(), 24, 60, 60); console.log("Result Date-Object: ", myDate);
    
    console.log("Result in Milliseconds: ", myDate.getTime());
    console.log("Today_Fullstring: ",  myDate);
    console.log("Date-String: ",  myDate.toDateString());
    console.log("Locale-String: ",  myDate.toLocaleString());
    console.log("Locale-Date-String: ",  myDate.toLocaleDateString());
    console.log("Locale-Time-String: ",  myDate.toLocaleTimeString());
    console.log("Time-String: ",  myDate.toTimeString());
});

function addHoursToDate(objDate, hour, min, sec) {console.log("running...");
    let numberOfMlSeconds = objDate.getTime(); console.log("Milliseconds-now: ", numberOfMlSeconds);
    let addHour = (hour * 60) * 60 * 1000; console.log("Milliseconds to add: ", addHour);
    let addMin =  min * 60 * 1000; console.log("Milliseconds to add: ", addMin);
    let addSec =  sec * 1000; console.log("Milliseconds to add: ", addSec);

    let newDateResult = new Date(numberOfMlSeconds + addHour + addMin + addSec); 
    console.log("-----------------------");
    return newDateResult;
}


Maybe this is not the best solution, maybe it can be done even much easier.

You can break down each DATE or time to a TIMESTAMP (in milliseconds).
TIMESTAMPS can be calculated.

You also could use the → set ← function of the DateObject to get your wished functionality.

Here some more infos…

1 Like