• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

198
Views
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 3 years ago · Juan Pablo Isaza
1 answers
Answer question

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 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error