-3

There is a strings as below:

2016,07,20,19,20,25

How can I transfer this strings to such as this format string:

2016-07-20 19:20:25

Thank you very much!

VatsalSura
  • 926
  • 1
  • 11
  • 27
Jacky Kwan
  • 61
  • 10

1 Answers1

0

A solution with array slice could be this

let parts = [];
let date = "2016,07,20,19,20,25"; 
let formatted = ((parts = date.split(",")).slice(0,3)).join("-") + ' ' + parts.slice(3).join(":")

You could also do it with String#replace and a function as the 2 argument;

let date = "2016,07,20,19,20,25"; 
date.replace(/,/g, (() => {
  let count = 0;
  return (match, position) => {
    count += 1;
    if(count == 3) return ' ';
    else if(count < 3) return '-';
    else return ':';        
  });
})())

Note: Both approaches assume that the format will always be the one provided 6 numbers seperated by commas

eltonkamami
  • 5,134
  • 1
  • 22
  • 30