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

331
Vistas
How to get current datetime seperated by a dash "-" in JS?

I'm trying to construct a nice file name. I tried to do it in 1 line in JS, but have not found anything yet. So I did these

const date = new Date().toLocaleDateString().replaceAll('/', '-').replaceAll('_', '-').replaceAll(' ', '-');
const time = new Date().toLocaleTimeString().replaceAll('/', '-').replaceAll('_', '-').replaceAll(' ', '-');
let dateTime = date + '-' + time;
console.log(dateTime);

I got

6-24-2022-3_38_18-PM

Why is the 2x _ underscores still there ??

GOAL

I'm trying to get

6-24-2022-3-33-17-PM

Do you guys know a better way to achieve that ?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

const date = new Date().toLocaleDateString().replaceAll('/', '-').replaceAll('_', '-').replaceAll(' ', '-')
const time = new Date().toLocaleTimeString().replaceAll('/', '-').replaceAll('_', '-').replaceAll(' ', '-')
console.log(date + '-' + time)

I see almost your desired result: 6-24-2022-3:48:11-PM (since you did not change : (colon) in time.

about 4 years ago · Juan Pablo Isaza Denunciar

0

better way to achieve that, instead use Moment.js

The format() method returns the date in specific format.

moment(new Date()).format("DD-MM-YYYY-hh-mm-ss-A");

NOTE: "A"-> 12H clock (AM/PM)

about 4 years ago · Juan Pablo Isaza Denunciar

0

Why is the 2x _ underscores still there ??

You are likely replacing something that isn't actually an underscore

Do you guys know a better way to achieve that?

Yes. Try using a RegExp

const date = new Date().toLocaleDateString().replace(/[^apm\d]+/gi, '-')
const time = new Date().toLocaleTimeString().replace(/[^apm\d]+/gi, '-')
let dateTime = date + '-' + time

console.log(dateTime)

This will remove anything that is not ([^...]+) an a p m or digit (\d).

/.../gi are the flags global and case-insensitive.

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