Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

223
Views
Adding seconds to javascript DateTime object through the use of a prompt

I have this webpage that takes in an input in seconds, and produces what the time will be after the time has elapsed. So I went about it using the following code


let duration = prompt("Enter your trip duration in seconds: ");  // get the time from the vaue of the input element

let newtime = new Date(); // get the current time
newtime.setSeconds(newtime.getSeconds() + duration)

I decided to test the code and it gave me weird results and for some reason when I divided the duration by ten it started to work. Even though it worked I wasn't satisfied. So I added some more code to try and find where the bug is.

let oldtime = new Date();
oldtime.setSeconds(oldtime.getSeconds() + 60);            

I added some code so that it would show on the webpage to compare the two times and these are my results when I enter 60 as the duration...

Code

Just a little summary. The code works when I hard code the values in but it behaves weirdly if I try get the input from a prompt

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You are concatenating a string to a number instead of adding. You have to parse the result from prompt to a number (with the unary plus operator):

let duration = prompt("Enter your trip duration in seconds: "); // get the time from the vaue of the input element

let newtime = new Date(); // get the current time
newtime.setSeconds(newtime.getSeconds() + +duration)
console.log(newtime)

about 4 years ago · Juan Pablo Isaza Report

0

I believe the issue is because you need to parse the duration from a string to number. So, try this

newtime.setSeconds(newtime.getSeconds() + parseInt(duration, 10))

about 4 years ago · Juan Pablo Isaza Report

0

You can use a library like Luxon to deal with dates and times without having to worry about unexpected behaviour like the one you described.

import { DateTime } from "luxon";

const now = DateTime.now();
const timeAfterTrip.plus({ seconds: duration });

console.log(timeAfterTrip);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!