Warm tip: This article is reproduced from stackoverflow.com, please click
javascript

Convert date and hours/minutes/seconds to correct format javascript

发布于 2020-03-27 10:24:35

I got date in format '20190702' and hours/minutes/seconds in format '125657' What is the easiest way to convert it to 07/02/2019, 12:56:57

const time = "125657";
  const chuncks = str.match(/.{1,2}/g).join(":"); //12:56:57

What about date?

Questioner
Palaniichuk Dmytro
Viewed
24
trincot 2019-07-03 22:59

The easiest is maybe this:

const time = "125657".replace(/(..?)(..)(..)/, "$1:$2:$3");
const date = "20190702".replace(/(....)(..)(..)/, "$2/$3/$1");

console.log(date, time);

The question mark in the first pattern could serve if the time string could have 5 digits instead of 6. If you are certain you always get 6 digits, you can leave it out.