1

In my react component I have an input field of type date. When a date is chosen it will be saved in state. In another place I want to add a certain number of days to this date and display it. I found Javascript solutions like this one (Add days to JavaScript Date) but unfortunately was not able to put it to use in my react/state environment. Any help on how to achieve this would be appreciated. Thanks!

Sidenote: I am using a local http server to load form.js

index.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
</head>
<body>
    <div class="form-container container col-8 my-4"></div>

    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

    <!-- Load our React component. -->
    <script type="text/babel" src="form.js" crossorigin></script>
</body>

form.js

'use strict';

const e = React.createElement;

class testForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        birthday: ''
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
      this.setState({ 
          birthday: event.target.value
        });
  }

  render() {
    return (
        <form>
            <div className="row">

                <div className="form-group">
                <label htmlFor="birthday">Birthday</label>
                <input type="date" className="form-control" id="birthday" value={this.state.birthday} onChange={this.handleChange} placeholder="TT.MM.JJJJ" />
                </div>

            </div>

            <div>Show date +7 days</div>
            <div>{this.state.birthday}</div>
        </form>
    );
  }
}

const domContainer = document.querySelector('.form-container');
ReactDOM.render(e(testForm), domContainer);

2 Answers2

1

Can use below function to add days to a given date.

function addDays(startDate,numberOfDays)
{
    var returnDate = new Date(
                            startDate.getFullYear(),
                            startDate.getMonth(),
                            startDate.getDate()+numberOfDays,
                            startDate.getHours(),
                            startDate.getMinutes(),
                            startDate.getSeconds());
    return returnDate;
}

This keeps things simple and makes for fairly reliable and readable code. By creating the date this way, the month and year adjust themselves based on the day of the month used. Thus if it is a negative number it will go to previous months and potentially years and the inverse for larger positive numbers.

heyitsvajid
  • 1,023
  • 1
  • 10
  • 19
0

If you need a simple solution, you can check my example on the codesandbox.

Here is a raw example:

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      birthday: ""
    };
  }

  handleBirthdayChange = event => {
    this.setState({
      birthday: event.target.value
    });
  };

  getDateInFuture = (leftBoundary, days) => {
    // Check if date is valid
    // e.g. '' -> invalid, '2018-01-01' -> valid, '1532034952667' -> invalid
    const isDateValid = Date.parse(leftBoundary);

    if (isDateValid) {
      const date = new Date(leftBoundary);
      const dateInFuture = new Date().setDate(date.getDate() + days);

      return new Date(dateInFuture);
    }

    // If date is incorrect, return today
    return new Date();
  };

  render() {
    return (
      <div className="App">
        <div>
          <label for="birthday">Birthday</label>
          <input
            id="birthday"
            type="date"
            value={this.state.birthday}
            onChange={this.handleBirthdayChange}
          />
        </div>
        <div>
          <p>
            The day in future:
            {this.getDateInFuture(this.state.birthday, 7).toString()}
          </p>
        </div>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Roman Mahotskyi
  • 4,576
  • 5
  • 35
  • 68