JavaScript Date as in YYYY-MM-DD hh:mm:ss
Format or MM/DD/YYYY hh:mm:ss
Javascript Date method is very crazy, we can achieve different date format with simple changes
Final code snippet here
function padTwoDigits(num: number) {
return num.toString().padStart(2, "0");
}
function dateInYyyyMmDdHhMmSs(date: Date, dateDiveder: string = "-") {
// :::: Exmple Usage ::::
// The function takes a Date object as a parameter and formats the date as YYYY-MM-DD hh:mm:ss.
// ποΈ 2023-04-11 16:21:23 (yyyy-mm-dd hh:mm:ss)
//console.log(dateInYyyyMmDdHhMmSs(new Date()));
// ποΈοΈ 2025-05-04 05:24:07 (yyyy-mm-dd hh:mm:ss)
// console.log(dateInYyyyMmDdHhMmSs(new Date('May 04, 2025 05:24:07')));
// Date divider
// ποΈ 01/04/2023 10:20:07 (MM/DD/YYYY hh:mm:ss)
// console.log(dateInYyyyMmDdHhMmSs(new Date(), "/"));
return (
[
date.getFullYear(),
padTwoDigits(date.getMonth() + 1),
padTwoDigits(date.getDate()),
].join(dateDiveder) +
" " +
[
padTwoDigits(date.getHours()),
padTwoDigits(date.getMinutes()),
padTwoDigits(date.getSeconds()),
].join(":")
);
}
Here is full story
First we have created padTwoDigits
function to leading zero to the day, month, hours, minutes and seconds if the value is less than 10
.means suppose date is 4th means we need it like 04
because the format we need like DD
two digits same for month, hours, minutes and seconds
function padTwoDigits(num: number) {
return num.toString().padStart(2, "0");
}
Next
we need year, month, and day these we will get from Javascript Date function using date = new Date(); date.getFullYear
, date.getMonth
date.getDate
same for hour hours, minutes, seconds date.getHours
date.getMinutes
date.getSeconds
suppose today date is 19th may 2023 and 10 AM by using above methods we get 2023, 5, 19 and 10 hours
in above for month we need to prepend 0 for month may using our padTwoDigits
lets join all using .join()
method thats here final code snippet
function padTwoDigits(num: number) {
return num.toString().padStart(2, "0");
}
function dateInYyyyMmDdHhMmSs(date: Date, dateDiveder: string = "-") {
return (
[
date.getFullYear(),
padTwoDigits(date.getMonth() + 1),
padTwoDigits(date.getDate()),
].join(dateDiveder) +
" " +
[
padTwoDigits(date.getHours()),
padTwoDigits(date.getMinutes()),
padTwoDigits(date.getSeconds()),
].join(":")
);
}
:::: Exmple Usage ::::
The function dateInYyyyMmDdHhMmSs
takes a Date object as a parameter, divider β β β or β / β and formats the date as YYYY-MM-DD hh:mm:ss.
ποΈ 2023β04β11 16:21:23
(yyyy-mm-dd hh:mm:ss)
console.log(dateInYyyyMmDdHhMmSs(new Date()));
2025β05β04 05:24:07
(yyyy-mm-dd hh:mm:ss)
Its All Javascript we can pass required date as well ποΈοΈ
dateInYyyyMmDdHhMmSs(new Date(βMay 04, 2030 10:20:07β), '/')
05/04/2030 10:20:07
Date divider β β β or β / β we can pass param
ποΈ 01/04/2023 10:20:07
(MM/DD/YYYY hh:mm:ss)
console.log(dateInYyyyMmDdHhMmSs(new Date(), β/β));
Thanks for reading, and happy coding!!!!