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

324
Views
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 answers
Answer question

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 Report

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 Report

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 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!