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

157
Views
¿Cómo agregar una hora para el formato de hora "24 horas" en javascript/jquery?

Quiero agregar una hora en formato de 24 horas usando Javascript o JQuery.

me gusta

si son las 23:00 deberian ser las 00:00
si son las 11:00 entonces las 12:00
si son las 13:00 entonces 14:00 si son las 09:00 entonces 10:00

para eso probé debajo del código. eso funciona perfectamente

 function increase24TimeByOne(timeStr) { var splitedTimeStr = timeStr.split(':'); var hours = parseInt(splitedTimeStr[0]); var minutes = splitedTimeStr[1].substring(0, 2); var nextHours = (hours + 1); if(nextHours.toString().length == 1){ nextHours = "0" + nextHours; } if(nextHours == 24){ nextHours = "00" } return nextHours + ":" + minutes; }

pero quiero saber que código es mejor o no?
¿Alguien puede sugerir?

Gracias por adelantado

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

0

Usando módulo matemático sumar 1 módulo 24

es decir (23 + 1) % 24 === 0

 function increase24TimeByOne(timeStr) { var splitedTimeStr = timeStr.split(':'); var hours = parseInt(splitedTimeStr[0]); var minutes = splitedTimeStr[1].substring(0, 2); var nextHours = (hours + 1) % 24; var nextMeridiem; if (nextHours.toString().length == 1) { nextHours = "0" + nextHours; } return nextHours + ":" + minutes; } console.log(increase24TimeByOne('23:45'))

Puede hacerlo mejor, convirtiendo a cadena Y relleno (opcionalmente) el '0' al mismo tiempo

usando toString().padStart(2, '0') - es decir, agregue '0' hasta que la cadena tenga al menos 2 de longitud

 function increase24TimeByOne(timeStr) { var splitedTimeStr = timeStr.split(':'); var hours = parseInt(splitedTimeStr[0]); var minutes = splitedTimeStr[1].substring(0, 2); var nextHours = ((hours + 1) % 24).toString().padStart(2, '0'); return nextHours + ":" + minutes; } console.log(increase24TimeByOne('23:45'))

En mi opinión, puede hacer esto incluso con menos código usando plantillas de cadena

Sin embargo, puede que no sea tan legible, pero menos código es mejor código (hasta cierto punto)

 function increase24TimeByOne(timeStr) { let [hours, minutes] = timeStr.split(':'); return `${((+hours + 1) % 24).toString().padStart(2, '0')}:${minutes}`; } console.log(increase24TimeByOne('23:45'))

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!