Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

279
Vistas
How to convert '20211114025320+0000' to JS date object

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?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

A function to parse the string and pass the parts directly the Date constructor may be more efficient than parsing the string to generate another string that is then parsed by the built–in parser.

This method also avoids the built–in parser, which is usually considered a good idea.

// Parse YYYYMMDDHHmmss±HHmm or YYYYMMDDHHmmssZ
function parseTS(ts) {
  // Get parts
  let [C,Y,M,D,H,m,s,sign,oH,oM] = ts.match(/\d\d|\D/g);
  // Deal with offset: ±HHmm or Z
  if (sign == 'Z') {
    sign = oH = oM = 0;
  }
  let oSign = sign == '+' ? -1 : +1;
  // Create date from parts, adjust H, m for offset
  return new Date(Date.UTC(C+Y, M-1, D, +H + oH*oSign, +m + oM*oSign, s));
}

['20211114082320+0530',
 '20211114025320+0000',
 '20211114025320Z',
 '20211113225320-0400'
].forEach(ts => console.log(ts + '\n' + parseTS(ts).toISOString()));

about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda