Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

225
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda