-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?

4
  • “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. The correct solution will look something like const { year, month, day, hour, minute, second } = theDateString.match(/(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})(?<hour>\d{2})(?<minute>\d{2})(?<second>\d{2})/).groups, result = new Date(year, month - 1, day, hour, minute, second);. Commented Jan 13, 2022 at 2: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. Commented Jan 13, 2022 at 2: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
    Commented Jan 13, 2022 at 4:28
  • To get the same format back: new Date().toLocaleString('en-CA').replace(/\D/g, '').
    – RobG
    Commented Jan 13, 2022 at 4:30

1 Answer 1

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())

1
  • Thanks! I did not realize that other people have asked the same question
    – benjm
    Commented Jan 13, 2022 at 13:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.