I have the following date format within a string:
"202112110836"
I want the string to be formatted with a dash -
separating the date and the hour separately in the following format:
"2021-12-11 08:36"
How can I achieve this in jQuery?
I have the following date format within a string:
"202112110836"
I want the string to be formatted with a dash -
separating the date and the hour separately in the following format:
"2021-12-11 08:36"
How can I achieve this in jQuery?
I don't think such a function exists in jQuery or JavaScript itself for that specific date format; the other solution is to simply fetch each subsection of the string and split it accordingly to the format you want.
const input = "202112110836";
// Fetch each specific date value by substring.
const year = input.substring(0, 4);
const month = input.substring(4, 6);
const day = input.substring(6, 8);
const hour = input.substring(8, 10);
const minute = input.substring(10, 12);
// Combine it all together.
const output = year + "-" + month + "-" + day + " " + hour + ":" + minute;
console.log(output);
We can try a regex replacement for one option:
var ts = "202112110836";
var output = ts.replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/, "$1-$2-$3 $4:$5");
console.log(ts + " => " + output);
Note that a more robust approach here would be to parse the text into a bona fide date, then render a text output using the format mask you don't want. I don't know if JS have a date/time API which can do this.