Skip to content

How to set user-defined time in Javascript and add 2 hours to it?

The user is providing time in the format of 12:00:00 (which is in string), and I want to add 1 or 3 hours to the time and show it as the end time.

The code:

function showCart(cart) {
  for (var i = 0; i < cart.length; i++) {
    var slotHtmlTr = '';
    var c = i + 1;
    slotHtmlTr += '<tr style="border: 1px solid black;" id="slot'+c+'">';
    slotHtmlTr += '<td style="border: 1px solid black;">Slot '+c+'</td>';
    slotHtmlTr += '<td style="border: 1px solid black;">'+cart[i].from_date+'</td>';
    slotHtmlTr += '<td style="border: 1px solid black;">'+cart[i].start_time+'</td>';
    slotHtmlTr += '<td style="border: 1px solid black;">End Time here</td>';
    slotHtmlTr += '<td style="border: 1px solid black;">'+cart[i].room_id+'</td>';
    slotHtmlTr += '<td style="border: 1px solid black;">'+cart[i].duration+'</td>';
    var slotPrice = (cart[i].duration == "1") ? 15 : 30;
    slotHtmlTr += '<td style="border: 1px solid black;">'+slotPrice+ '</td>';
    slotHtmlTr += '</tr>';
  // console.log(slotHtml);

How I am adding the time:

let hrsAdd = 3;
let start_time = cart[i].start_time;
let end_time = new Date(start_time); //showing some error
console.log(end_time + hrsAdd);

I know I am doing something wrong, but can’t figure out what?

Thanks in advance!



You have to remember that Date class has some limitation on creating it, so you may not just set your time on the constructor, it must be in a specific format. For more details take a look on the JS Date class documentation.

Your time calculation can be done with a similar code to this:

srcTime = "12:01:02"; // value sent by the user
baseDateTime = new Date(); // the date does not matter to us, but it comes together as it is the Date class
[srcHour, srcMinute, srcSecond] = srcTime.split(":"); // we separate the value in the right variables
baseDateTime.setHours(parseInt(srcHour) + 3); // update the Date object with user hour + 3 hours

// from this point on you can work with the baseDateTime variable to extract the time, date and etc.
// for example:
end_time = baseDateTime.getHours() + ":" + baseDateTime.getMinutes() + ":" + baseDateTime.getSeconds();

User contributions licensed under: CC BY-SA
8 People found this is helpful