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 ?
CodePudding user response:
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.
CodePudding user response:
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)
CodePudding user response:
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.