date-fns | display date

Issue

I have a function that formats date strings as shown below.

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

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

My articles contain data like this:

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

To format the dates, I use the convertDate function like this:

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

Currently, I am encountering an error: https://i.sstatic.net/MoJpP.png

Desired outcome:

https://i.sstatic.net/HJHly.png

Alternatively, I can use

{convertDate(article.date, "PPP")}
which also produces the correct result.

Any assistance would be greatly appreciated!

Answer №1

Upon running the provided example on runkit.com, the output obtained was "2022" without encountering the reported error:

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"

Therefore, the source of the error lies elsewhere.

Moreover, using new Date in the function is deemed unnecessary:

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

is considered adequate and more resilient.

It has been recommended in other discussions that extracting the year from the timestamp can be accomplished through string manipulation, obviating the necessity for conversion to a Date. To extract 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 a Date object is required for other purposes (e.g., obtaining formatted month names), it is advisable to cast it to a Date once and reuse it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Unable to access attributes of null object (specifically 'accessToken')

After following a YouTube tutorial by Lama for creating an E-commerce application, I attempted to add a logout feature on the admin page that was not covered in the tutorial. To implement this, I used Redux to grab the currentUser and set it to null to suc ...

In my current project, I've noticed that while everything is being parsed correctly in the JSON data, there is one element that is consistently returning null even though it

Every time I attempt to parse the messages, it consistently returns nil. While occasional errors would be understandable, this recurring issue suggests a deeper problem at play. Reviewing the console output reveals: commitJson(sha: "3665294d1e813d35594d6 ...

Add delayed event listeners to embedded AJAX request beyond function boundaries

I'm working on developing a custom AJAX method extension named getApi that automatically includes my authentication bearer token in the request header. In my code, there is a function called getToken() which retrieves the token either from sessionSto ...

I am attempting to activate the "about us" button on the website. I have successfully included the path and added a router link to the containing div of the button. However, there seems to be something

In my app, the first step involves specifying the path in the routing module. Following that is defining the home component, then the app component, and finally creating the button using HTML. Setting up the path in the app.routing.module.ts file <div ...

What action should be taken if there is only one choice in a SELECT statement?

I have created a dynamic form with three interconnected select elements. The first select element is populated with data fetched from a MySQL database using PHP. The second select element is populated based on the selection made in the first one, triggered ...

Mocking a third-party callback function in Jest for method implementation

Utilizing Nest + Cognito for user authentication in an application, I have a method within my Authentication service that requires testing/mocking: async cognitoRegister(userPool: CognitoUserPool, { name, password, email }: AuthRegisterInput): ...

Counting up in Angular from a starting number of seconds on a timer

Is there a way to create a countup timer in Angular starting from a specific number of seconds? Also, I would like the format to be displayed as hh:mm:ss if possible. I attempted to accomplish this by utilizing the getAlarmDuration function within the tem ...

Steps for integrating a Facebook Messenger chatbot with a MongoDB database in order to submit requests and retrieve responses through conversations with the bot

I am currently working on integrating my Facebook Messenger chatbot with a MongoDB database. The chatbot I have created is a simple questionnaire chatbot that takes text inputs and displays buttons with options. When a user clicks on a button, it should ...

React: Struggling to render values within {} of a multidimensional object

I'm facing a challenge that I can't seem to overcome and haven't found a solution for. The values between curly braces are not displaying in the Content and Total components. I've double-checked the JSX rules, but it seems like I might ...

Why is my Javascript for-loop returning "null" instead of the expected value?

Having trouble with the function below that is supposed to calculate the average of all elements in array1. Unfortunately, the function keeps returning null as the result. I can't seem to pinpoint the issue. var array1 = [46,73,-18,0,-442,779,5,1400] ...

Is there a way to switch between showing and hiding all images rather than just hiding them one by one?

Is there a way I can modify my code to create a button that toggles between hiding and showing all images (under the user_upload class), instead of just hiding them? function hidei(id) { $('.user_upload').toggle(); Any suggestions would be grea ...

PHP is encountering a duplication issue with the JSON output

My current goal is to store the JSON return result into a TXT file. However, I am encountering an issue where each iteration in the array includes all previous numbers. For instance, the first iteration only takes the first number in the array $array_1, bu ...

Having trouble with typecasting in Angular 9 after receiving an HTTP response?

When initializing my component, it fetches student information from an API. Here is the ngOnInit code for component-version1: ngOnInit(): void { if(!this.student) { this.studentsService.getStudentDetail(this.id).subscribe( (response: Stu ...

Displaying an element as a dropdown menu on PrimeVue

I have a challenge with rendering a Dropdown using PrimeVue with the given script: <template lang="pug"> Dropdown#tag(v-model="tag" :options="tags") </template> <script setup> import axios from 'axios&a ...

Static express is failing to load the node_modules folder

Why am I facing difficulties with my website not being able to use the node_modules directory on my server? const express = require('express'); const app = express(); app.use(express.static(__dirname + '/public')); app.listen(8080, &ap ...

Displaying nested objects within an object using React

Behold this interesting item: const [object, setObject] = useState ({ item1: "Greetings, World!", item2: "Salutations!", }); I aim to retrieve all the children from it. I have a snippet of code here, but for some reason, i ...

Setting up a NextJS development server in a docker environment with networking

Currently, my development environment consists of a NextJS app running in a docker-compose setup under the name frontend. The backend is powered by an expressjs app known as backend. In my NextJS app, there's an environment variable that specifies t ...

Heroku is showing an Error R10 (Boot timeout) message, indicating that the web process was unable to bind to the designated $PORT within one minute of launching

Encountering an error while trying to deploy my first node project on Heroku. Here is the error message: 2020-09-29T04:24:09.365962+00:00 app[web.1]: production 2020-09-29T04:24:09.415266+00:00 app[web.1]: server is listening at port 40890 2020-09-29T04:24 ...

Angular allows for the creation of dynamic and interactive scenes using Canvas and Three.js

I am in the process of developing a collection of web apps within an Angular SPA. Each individual application is encapsulated within an Angular template, and when navigating between them, specific DOM elements are replaced and scripts from controllers are ...

How can I utilize JSON data to retrieve information using D3 library?

Currently, I am experimenting with learning D3 JS and endeavoring to create a bar chart using real-time data fetched from the openweather API. My aim is to display the City Name along with its corresponding temperature at the time of the query. However, a ...