Paulo Rodrigues
Paulo Rodrigues

Reputation: 407

Formatting date React

How can I arrange the date in the proper format?

On the screen the date wrong, it shows 32/03/2020 but day 32 does not exist.

The correct format date is on the image below. I am new with Reactjs, what has gone wrong in my code and how can I solve it?

My code is below:

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>
                    )

The format is on the image below:

img example

Upvotes: 0

Views: 61

Answers (1)

Guruparan Giritharan
Guruparan Giritharan

Reputation: 16334

What you need is a padding function something like below

const padNumber = (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 = `${padNumber(day)}/${padNumber(month)}/${year}`;
  return formattedString;
};

Still the easiest way would be using moment.js

Upvotes: 1

Related Questions