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

255
Vistas
date-fns | format date

Problem

I have below function that formats date string.

import { format, parseISO } from "date-fns";

export function convertDate(myDate, displayFormat) {
    return format(new Date(parseISO(myDate)), displayFormat);
}

I have articles that has content such as

title: 'My title'
date: '2022-01-04'

I call the convertDate function using below:

if (articles) {
        for (let i = 0; i < articles.length; i++) {
            const year = convertDate(articles[i].date, "y");
            years.push(year);
        }
        uniqueYear = [...new Set(years)];
    }

My timezone is CEST.

Error

I am getting error: Error

Expected result:

Result

I can call the function by using {convertDate(article.date, "PPP")} which also works.

Please help!

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

0

Running the following minimal example at runkit.com returns "2022", it doesn't throw the error described in the OP:

var dateFns = require("date-fns")

function convertDate(myDate, displayFormat) {
    return dateFns.format(new Date(dateFns.parseISO(myDate)), displayFormat);
}

let articles = [{
  title: 'My title',
  date: '2022-01-04'
}];

convertDate(articles[0].date, "y"); // "2022"

So the error is elsewhere.

Also, the use of new Date is redundant:

dateFns.format(dateFns.parseISO(myDate), displayFormat)

is sufficient and more robust.

As suggested elsewhere, getting the year from the timestamp can be done using string manipulation, no need for casting to a Date. To get the years:

let articles = [{title: 'title 0', date: '2022-01-04'},
                {title: 'title 1', date: '2020-01-04'}];

let years = articles.map(o => o.date.substring(0,4));

console.log(years);

If you need it as a Date for other things (e.g. formatted month name), cast it to a Date once and reuse it.

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