0

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?

Skully
  • 2,882
  • 3
  • 20
  • 31
ramin
  • 448
  • 4
  • 15
  • 3
    Just asking for a solution won't help, show us what you have tried so far, what issues you ran into. – Pramod Karandikar Dec 13 '21 at 05:25
  • 3
    jQuery has no string or date methods that will be of use here. What research have you done and what have you tried? – charlietfl Dec 13 '21 at 05:25
  • I used slice() and solved my problem – ramin Dec 13 '21 at 05:41
  • Well that was pretty quick. You probably didn't need to ask this question at ll then – charlietfl Dec 13 '21 at 05:44
  • 1
    [Duplicate](//google.com/search?q=site%3Astackoverflow.com+js+parse+arbitrary+date+format) of [Converting a string to a date in JavaScript](/q/5619202/4642212) and [How to format a JavaScript date](/q/3552461/4642212). – Sebastian Simon Dec 13 '21 at 05:48
  • @charlietfl At first it seemed very difficult to me. But I found it [link](https://www.w3schools.com/jsref/jsref_slice_string.asp) . I had to go to him before asking. – ramin Dec 13 '21 at 05:50
  • 1
    If you really have an YMD date, it's not possible to reliably parse it to anything. – Teemu Dec 13 '21 at 05:50

2 Answers2

2

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);
Skully
  • 2,882
  • 3
  • 20
  • 31
2

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360