Styling dates in React

How can I properly display the date in the correct format?

I'm seeing the date displayed incorrectly on the screen as 32/03/2020, but the 32nd day doesn't exist.

Below is the correct date format displayed in the image. I'm new to Reactjs, can you help me identify the issue in my code and suggest a solution?

Here is my code:

class Chamado extends Component {
  constructor(props) {
    super(props);

    this.state = {
      offset: 0,
      pageCount: this.props.chamados.length / this.props.perPage,
    };

    this.formatDate = this.formatDate.bind(this);
    this.handlePageClick = this.handlePageClick.bind(this);
  }

  formatDate(date) {
    const dateObject = new Date(date);
    const day =
      dateObject.getDate() + 1 < 10
        ? '0' + (dateObject.getDate() + 1)
        : dateObject.getDate() + 1;
    const month =
      dateObject.getMonth() + 1 < 10
        ? '0' + (dateObject.getMonth() + 1)
        : dateObject.getMonth() + 1;
    const year = dateObject.getFullYear();
    const formattedString = `${day}/${month}/${year}`;

    return formattedString;
  }

  handlePageClick(data) {
    let selected = data.selected;
    let offset = Math.ceil(selected * this.props.perPage);

    this.setState({
      offset: offset,
    });
  }

  render() {
    const props = this.props;

    return (
      <SC.Container>
        <SC.Title>
          Histórico de <b>Chamados</b>
          {this.props.chamados.length !== undefined && (
            <SC.Add
              title="Abrir um novo chamado"
              onClick={(event) => props.setViewAbrirChamados(true)}
            >
              <GoPlus size="21px" color="#FFF" />
            </SC.Add>
          )}
        </SC.Title>
        <SC.List>
          {this.props.chamados.length !== undefined ? (
            <React.Fragment>
              {props.chamados.length > 0 &&
                props.chamados.map((item, index) => {
                  const maxOffset = this.state.offset + (props.perPage - 1);

                  return (
                    index >= this.state.offset &&
                    index <= maxOffset && (
                      <SC.Item key={item.id}>
                        <SC.Info>
                          <SC.Details>
                            <p>
                              <b>
                                {item.id} |{' '}
                                {item.titulo || item.categoria.descricao}
                              </b>
                            </p>
                            <p>
                              {this.formatDate(item.data_abertura)} -{' '}
                              {item.hora_abertura}
                            </p>
                          </SC.Details>
                        </SC.Info>
                        <SC.Buttons
                          onClick={(event) => {
                            props.setViewChamadoInfo(true, item.id);
                          }}
                        >
                          <button>
                            <FaInfo size="24" color="#fff" />
                          </button>
                        </SC.Buttons>
                      </SC.Item>
                    )

For reference, the correct date format can be seen in the image below:

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

Answer №1

To achieve the desired outcome, you can create a padding function as shown below:

const addPadding = (number) => {
  if (number.toString().length === 1) return `0${number}`;

  return number;
};

const formatDate = (date) => {
  const dateObject = new Date(date);
  const day = dateObject.getDate();
  const month = dateObject.getMonth() + 1;
  const year = dateObject.getFullYear();
  const formattedString = `${addPadding(day)}/${addPadding(month)}/${year}`;
  return formattedString;
};

Alternatively, you could also make use of moment.js for a simpler solution.

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

The date error from day.js in Firefox is not valid

My date is formatted as 2022-01-27 09:23:48 UTC and I am trying to parse it into MMMM-DD-YYYY format (Jan-27-2022) using day.js. The parsing works well in Chrome, but Firefox returns an 'Invalid' result. import dayjs from "dayjs" const ...

Generating HTML output in Express using React ES6

In my React Application, I have coded all my Components in ES6 style. Here is an example of how they are built: import React, { Component } from 'react'; class Test extends Component { render() { return ( <div classNa ...

"Enhance readability by adjusting the font size on mobile devices and iPhones for an

I'm currently working on a website that needs to maintain a consistent look across all types of devices, including laptops, PCs, iPads, iPhones, and other smartphones. To achieve this, I've implemented fittext.js, a pure JavaScript solution that ...

Issue with calling function from props in React is not being resolved

There seems to be an issue with the function not being called when passed into a functional component. While the onSubmit function is triggered, the login(email, password) function inside the Login component is never executed. Despite placing console.log s ...

Tips for positioning text on the left and right sides of a div in HTML styling

I am struggling with positioning two pieces of text within a div. Despite having some styling already in place, the text is currently displaying one after the other on the left-hand side. I want to position one piece of text to the left and another to the ...

Designing links within a web application

Currently, I am developing a web application that will contain a high volume of clickable elements. The challenge lies in maintaining a visually appealing design while adhering to web best practices such as using different colors and underlines for links. ...

Converting a Complex Array of Objects into a CSV File for Download in a React Application

My current data is available for download in xls/csv format, but when using the react-csv npm package, the name and description are being displayed in the same column instead of separate columns. I am seeking assistance on how to display the data with Nam ...

Equal spacing title in horizontal menu with Bootstrap design

Is there a way to evenly distribute menu links with varying text lengths in equal width bootstrap columns? Adjusting the column class between col-md-1 and col-md-3 doesn't seem to give accurate spacing. If you want to see, I've set up a fiddle h ...

Tips for creating SCSS shorthand for an Array value color within a property

I've got a SCSS file containing an array of color values. export const COLORS = { transparent: 'rgba(0,0,0,0)', primary: '#09596e', primary01: '#317D92', primary02: '#6BADBF', primary03: '#97C6D2& ...

Utilize ngFor in Angular Ionic to dynamically highlight rows based on specific criteria

I'm working on an application where I need to highlight rows based on a count value using ngFor in Angular. After trying different approaches, I was only able to highlight the specific row based on my count. Can someone please assist me? Check out m ...

Create styles for each component based on their specific props when designing a customized Material-UI theme

I am having trouble styling the notchedOutline of a disabled <OutlinedInput /> in my custom MUI theme. My goal is to make the border color lighter than the default color when the input is disabled. Here is what I have attempted so far: const theme = ...

Modify the state from a listener that is enclosed in the useEffect function

Within my hook called useQueryEvents, I have a setup that involves fetching all past transactions for a user and listening to the network for incoming/outgoing transactions. These transactions are then passed into a function called addActionToActivity, whi ...

Customizing CSS for displayed MDBootrap components

I am currently using MDBoostrap, a styling tool similar to Bootstrap, in my React application. I have a select element that is coded like so: <div> <select id="Regions" style={errorSelect} value={this.state.userRegionId} onChange={this.handle ...

Make sure PTable maintains a horizontal layout on any device with PrimeNG

When I view my Ptable on desktop or iPad, it looks like this: https://i.stack.imgur.com/ONqZV.png However, when I switch to a device like an iPhone X, it changes to this layout: https://i.stack.imgur.com/H2q7j.png I want the horizontal layout to displa ...

React Tetris game always returns false in its function

Within my react project, I am working with a 2D array containing numbers. I have implemented a function called collisionCheck that iterates through the array to check for specific values. My goal is for this function to return true and exit when it encou ...

Scrolling left and right, text floats atop the image

Trying to implement a rollover effect image using CSS. The initial state shows only the title, but upon hovering, a text overlay appears. Everything seems to be working well except that the text area extends off to the right. Also, there is scrolling up an ...

Ways to display only particular dates in react-dates

I am working with an array of dates. const availableDates = ["2019-02-01", "2019-02-04", "2019-02-05", "2019-02-06", "2019-02-07", "2019-02-11", "2019-02-12", "2019-02-13", "2019-02-14", "2019-02-15", "2019-02-19", "2019-02-20", "2019-02-21", "2019-02-22" ...

The React Hook useEffect is missing dependencies which are 'match.params.id' and 'match.params.type'. You must either include them in the dependency array or remove them altogether

Hello everyone, I have created a movie app using a movie database API. When I navigate to the detail page, I check the React Router props match.params and fetch data with axios like this: Router <Route exact path="/:type/detail/:id" component ...

Customize the colors of the arrows in Bootstrap's carousel

There seems to be a simple solution that I'm missing here. I have images with white backgrounds and I want to customize the arrows on Bootstrap's Carousel to make them more visible. I need help changing the color of the arrows (not the background ...

The animation did not cause a transition to occur

After creating a search modal triggered by jQuery to add the class -open to the main parent div #search-box, I encountered an issue where the #search-box would fade in but the input did not transform as expected. I am currently investigating why this is ha ...