Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

228
Visualizações
Regex to reorder parts of date in javascript

I have a date and a format for that date, given by the user. (d.m.yyyy and 15.10.2021 used for this example)

From that format, I need to get the position of the year, month and day, so that I can use that position on the date.

const year = /y{4}|y{2}/.exec(format);
const month = /m{1,2}/.exec(format);
const day = /d{1,2}/.exec(format);

const yearVal = date.substring(year.index, year.index + year[0].length);

The problem with this is that the format has 1 letter, but my date has 2 numbers. (d and 15.) So i get 0.20 instead of 2021 How can i change this to work with all the different formats?

You can see all the possible formats here: node-dateformat

For example: the difference between "d" and "dd" are like this:

"d" Day of the month as digits; no leading zero for single-digit days.

"dd" Day of the month as digits; leading zero for single-digit days.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You could generate a regex from the pattern like this:

format.replace(/([ymd])\1*/g, (match, ymd) => `(?<${ymd}>${'\\d'.repeat(match.length)})`);

yyyy-mm-dd will become /(<?y>\d\d\d\d)-(<?m>\d\d)-(<?d>\d\d)/, then you can extract the year/month/day using group names:

function getDates(format, date) {
  const regex = new RegExp(format.replace(/(\w)\1+|(\w)/g, ({length}, w, s) => `(?<${w||s}>${s ? '\\d+' : '\\d'.repeat(length)})`));
  const result = date.match(regex);
  if(result) {
    const { y: year, m: month, d: day } = result.groups;
    return { year, month, day };
  }
}


console.log(getDates('yyyy-mm-dd', '2021-10-15'));
console.log(getDates('dd/mm/yyyy', '15/10/2021'));
console.log(getDates('mm-dd-yy', '10-15-21'));

console.log('----');

console.log(getDates('yyyy-m-d', '2021-9-15'));
console.log(getDates('yyyy-m-d', '2021-10-6'));

about 4 years ago · Juan Pablo Isaza Relatório

0

Another option here to split the format & value, lookup y/m/d at respective index

const lookup = ( format, value ) => {
    const f = format.split(/(m+|d+|y+)/).filter(Boolean);
    const v = value.split(/(\D+)/).filter(Boolean);
    return [
        v[f.findIndex(i => i.startsWith('y'))],
        v[f.findIndex(i => i.startsWith('m'))],
        v[f.findIndex(i => i.startsWith('d'))]
    ];
}
console.log(lookup('d.m.yyyy', '10.5.2021'));
console.log(lookup('d.m.yyyy', '10.12.2021'));
console.log(lookup('dd.mm.yyyy', '10.05.2021'));
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda