Lex V
Lex V

Reputation: 1447

Want to display last day of last month in reactjs

enter image description here

I want to initially display the last month's last date, for example, this is November, I want to display 31/10/2019. How is it possible?

      var date = new Date();
        date.setMonth(date.getMonth())
        const firstDayOfCurrent = new Date(date.getFullYear(), date.getMonth(), 0);
        const firstDayOfCurrentMonth = moment(firstDayOfCurrent).format('MM/DD/YYYY')
        console.log(firstDayOfCurrentMonth);

 <td><input type="date" value={firstDayOfCurrentMonth} onChange={(e) => { this.state.invoice.InvoiceDateString  = e.target.value; this.setState({ isset: true }); }} required /></td>

Upvotes: 0

Views: 880

Answers (3)

Nouman Janjua
Nouman Janjua

Reputation: 410

This code snippet will give you last date of last month

var date = new Date();
date.setMonth(date.getMonth())
var lastDay = new Date(date.getFullYear(), date.getMonth(), 0);
var lastDayOfLastMonth = lastDay.toISOString().substr(0, 10);

and your input tag

<input type="date" defaultValue={lastDayOfLastMonth } required />

Upvotes: 1

Domino987
Domino987

Reputation: 8774

I would recommend to use date-fns, which has a ton of helper functions you could use for that use-case.

For example lastDayOfMonth, which returns the last day of the month.

It also allows tree-shacking, so that you do not import the whole library, but only the functions you use.

Upvotes: 0

Andres
Andres

Reputation: 1012

You can take month from current date to take first day of current month and then subtract one day:

const today = new Date();
const firstDayOfCurrentMonth = new Date(today.getFullYear(), today.getMonth(), -1);
``

Upvotes: 1

Related Questions