Home > OS >  How to convert '20211114025320 0000' to JS date object
How to convert '20211114025320 0000' to JS date object

Time:11-16

I need to convert string: '20211114025320 0000' to JS Date object (2021-11-14T02:53:20.000Z).

I have this format for info ('YYYYMMDDHHmmssZ') maybe I need to use a custom function for this?

CodePudding user response:

It looks like what you have is an ISO 8601 string with all the separators stripped away.

Therefore, a straight-forward way would be to add these separators back using a regex replace and then parsing it using the built-in parser:

function parseCustomDate (s) {
  const isoString = s.replace(/^(....)(..)(..)(..)(..)(.*)$/, '$1-$2-$3T$4:$5:$6')
  return new Date(isoString)
}

(Note that here the last capture group with the .* captures both seconds and the timezone specifier at once, because those don't need a separator between them anyway. To make it clearer, you could also use (..)(.*) and $6$7 instead of only (.*) and $6 as I did.)


Another way that is faster computationally but also more complex to read, understand and catch bugs in (in my opinion at least) would be to take the individual parts of the string and pass them to the Date.UTC constructor instead of going through the ISO string route:

function parseCustomDate (s) {
  const year = Number(s.slice(0, 4))
  const month = Number(s.slice(4, 6))
  const day = Number(s.slice(6, 8))
  const hour = Number(s.slice(8, 10))
  const minute = Number(s.slice(10, 12))
  const second = Number(s.slice(12, 14))
  const tzSign = s.slice(14, 15)
  const tzHour = Number(tzSign   s.slice(15, 17)) || 0
  const tzMinute = Number(tzSign   s.slice(17, 19)) || 0
  return new Date(Date.UTC(
    year, month - 1, day,
    hour - tzHour, minute - tzMinute, second
  ))
}

Explanation for the timezone handling here: JavaScript accepts "invalid" dates that have individual parts outside of the regular range by rolling them over, so e.g. 11:70:00 would become 12:10:00. This is why we can simply subtract the timezone parts (with each part also capturing the /- sign), and we don't even have to mess with multiplying the minutes by 60 because we can handle them in the minutes part too.

I added the || 0 so that a string with a Z as timezone which would otherwise make tzHour and tzMinute NaN would also be handled as zero timezone offset.

  • Related