Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda