-4

I got this string from an api After looking at it I realized it was a dat/time

20220112201146

I then decoded it by hand to be

2022(Y)01(M)12(D)20(H)11(M)46(S)

How would I slice everything up to be Y:M:D:H:M:S? Example:

2022:01:12:20:11:46

And then add 80 mins to it?

Phil
  • 157,677
  • 23
  • 242
  • 245
benjm
  • 57
  • 1
  • 14
  • _“Note: Parsing of date strings with the `Date` constructor (and `Date.parse`, which works the same way) is **strongly discouraged** due to browser differences and inconsistencies.”_ — From the [documentation](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#parameters). The correct solution will look something like `const { year, month, day, hour, minute, second } = theDateString.match(/(?\d{4})(?\d{2})(?\d{2})(?\d{2})(?\d{2})(?\d{2})/).groups, result = new Date(year, month - 1, day, hour, minute, second);`. – Sebastian Simon Jan 13 '22 at 02:02
  • Then, simply `result.setMinutes(result.getMinutes() + 80);` and ``const stringResult = `${String(result.getFullYear()).padStart(4, "0")}:${String(result.getMonth() + 1).padStart(2, "0")}:${String(result.getDate()).padStart(2, "0")}:${String(result.getHours()).padStart(2, "0")}:${String(result.getMinutes()).padStart(2, "0")}:${String(result.getSeconds()).padStart(2, "0")}`;`` for the format. – Sebastian Simon Jan 13 '22 at 02:11
  • 1
    `let [C,Y,M,D,H,m,s] = '20220112201146'.match(/\d\d/g); new Date(C+Y, M-1, D, H, m, s)`. That simple. – RobG Jan 13 '22 at 04:28
  • To get the same format back: `new Date().toLocaleString('en-CA').replace(/\D/g, '')`. – RobG Jan 13 '22 at 04:30

1 Answers1

1

Extract the various parts (year, month, day, etc) via regex, transform it to ISO 8601 format, parse it to a Date instance, then add 80 minutes

const str = "20220112201146"

const rx = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/
const iso8601 = str.replace(rx, "$1-$2-$3T$4:$5:$6")
console.log("iso8601:", iso8601)

const date = new Date(iso8601)
console.log("original date:", date.toLocaleString())

date.setMinutes(date.getMinutes() + 80)
console.log("future date:", date.toLocaleString())
Phil
  • 157,677
  • 23
  • 242
  • 245